GPIO输入按键检测(使用STM32Cube_FW_F4_V1.16.0固件库)

每按一下按键,LED灯就变一个颜色。

key.h:

#ifndef __KEY_H__
#define __KEY_H__

#include "stm32f429xx.h"
#include "stm32f4xx_hal_gpio.h"
#include "stm32f4xx_hal_rcc.h"

void Key_GPIO_Config(void);
uint8_t Key_Scan(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);

#endif

key.c:

#include "key.h"

void Key_GPIO_Config(void)
{
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    
    GPIO_InitTypeDef init;
    init.Alternate = 0;
    init.Mode = GPIO_MODE_INPUT;
    init.Pull = GPIO_NOPULL;
    init.Speed = 0;
    
    init.Pin = GPIO_PIN_0;
    HAL_GPIO_Init(GPIOA, &init);
    
    init.Pin = GPIO_PIN_13;
    HAL_GPIO_Init(GPIOC, &init);
}

uint8_t Key_Scan(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
    if (HAL_GPIO_ReadPin(GPIOx, GPIO_Pin) == GPIO_PIN_SET)
    {
        while (HAL_GPIO_ReadPin(GPIOx, GPIO_Pin) == GPIO_PIN_SET);
        return GPIO_PIN_SET;
    }
    return GPIO_PIN_RESET;
}

main.c:

#include "led.h"
#include "key.h"

void SetLedColor(int nLedColor)
{
    switch (nLedColor)
    {
        case 1: { LED_RED; break; }
        case 2: { LED_GREEN; break; }
        case 3: { LED_BLUE; break; }
        case 4: { LED_YELLOW; break; }
        case 5: { LED_PURPLE; break; }
        case 6: { LED_CYAN; break; }
        case 7: { LED_WHITE; break; }
        case 8: default: { LED_ALL_OFF; break; }
    }
}

int main(void)
{
    Led_GPIO_Config();
    Key_GPIO_Config();
    
    int nLedColor = 8;
    SetLedColor(nLedColor);
    
    while (1)
    {
        if (Key_Scan(GPIOA, GPIO_PIN_0) == GPIO_PIN_SET)
        {
            nLedColor++;
            nLedColor = nLedColor > 8 ? 1 : nLedColor;
            SetLedColor(nLedColor);
        }
        else if (Key_Scan(GPIOC, GPIO_PIN_13) == GPIO_PIN_SET)
        {
            nLedColor--;
            nLedColor = nLedColor < 1 ? 8 : nLedColor;
            SetLedColor(nLedColor);
        }
    }
}

posted @ 2017-06-21 00:51  UnrealLearner  阅读(952)  评论(0编辑  收藏  举报