主程序:
#include "bsp_key.h"
static KEY_T s_tBtn[KEY_COUNT];
int main(void)
{
uint8_t key_val = 0;
for( ;; )
{
key_val = bsp_KeyScan();
if(key_val)
{
LED_ON();
vTaskDelay(50);
LED_OFF();
printf("KEY:%2x\r\n",key_val);
}
vTaskDelay(10); //10s
}
}
(1)按键GPIO初始化,给按键赋缺省值
void key_gpio_init(void)
{
//PF14(UP),PC14(DOWN),PA0LEFTP),PF13(RIGHT),PF14(OK)
rcu_periph_clock_enable(RCU_GPIOA);
rcu_periph_clock_enable(RCU_GPIOC);
rcu_periph_clock_enable(RCU_GPIOF);
rcu_periph_clock_enable(RCU_GPIOG); //LED1
/* configure LEDs GPIO port */
gpio_init(GPIOA, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_0);
gpio_init(GPIOC, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_13);
gpio_init(GPIOF, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);
gpio_init(GPIOG, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_11); //LED1
bsp_InitKeyVar();
}
static void bsp_InitKeyVar(void)
{
uint8_t i;
/* 给每个按键结构体成员变量赋一组缺省值 */
for (i = 0; i < KEY_COUNT; i++)
{
s_tBtn[i].Wait=0;
s_tBtn[i].Count=0;
s_tBtn[i].LongState=0;
}
/* 判断按键按下的函数 */
s_tBtn[0].IsKeyDownFunc = IsKeyDown1;
s_tBtn[1].IsKeyDownFunc = IsKeyDown2;
s_tBtn[2].IsKeyDownFunc = IsKeyDown3;
s_tBtn[3].IsKeyDownFunc = IsKeyDown4;
s_tBtn[4].IsKeyDownFunc = IsKeyDown5;
}
(2)查询,并返回按键
uint8_t bsp_KeyScan(void)
{
uint8_t i;
for (i = 0; i < KEY_COUNT; i++)
{
if(bsp_DetectKey(i))
{
return 1+i;
}
}
return 0;
}
uint8_t bsp_DetectKey(uint8_t x)
{
if(s_tBtn[x].IsKeyDownFunc())
{
vTaskDelay(10);
if(s_tBtn[x].IsKeyDownFunc())
{
s_tBtn[x].Wait =1;
s_tBtn[x].Count++;
if(s_tBtn[x].Count>20)
{
s_tBtn[x].LongState=1;
s_tBtn[x].Count=0;
}
else
{
s_tBtn[x].LongState=0;
}
}
}
if(!s_tBtn[x].IsKeyDownFunc())
{
s_tBtn[x].Count=0;
s_tBtn[x].LongState=0;
if(s_tBtn[x].Wait ==1)
{
s_tBtn[x].Wait =0;
return 1;
}
}
return 0;
}
static uint8_t IsKeyDown1(void)
{
return KEY_DOWN_Val;
}
static uint8_t IsKeyDown2(void)
{
return KEY_UP_Val;
}
static uint8_t IsKeyDown3(void)
{
return KEY_LEFT_Val;
}
static uint8_t IsKeyDown4(void)
{
return KEY_RIGHT_Val;
}
static uint8_t IsKeyDown5(void)
{
return KEY_OK_Val;
}
(3)#include "bsp_key.h" 文件
typedef struct
{
/* 下面是一个函数指针,指向判断按键手否按下的函数 */
uint8_t (*IsKeyDownFunc)(void); /* 按键按下的判断函数,1表示按下 */
uint8_t LongState; // 1:长按状态
uint8_t State; // 1:弹起 0:按下
uint8_t Wait; // 1:按下后等待弹起
uint16_t Count; /* 计数器 */
}KEY_T;
void key_gpio_init(void);
uint8_t bsp_KeyScan(void);
uint8_t bsp_DetectKey(uint8_t );
static void bsp_InitKeyVar(void);
#define KEY_COUNT 5
#define LED_ON() gpio_bit_set(GPIOG, GPIO_PIN_11);
#define LED_OFF() gpio_bit_reset(GPIOG, GPIO_PIN_11);
#define KEY_UP_Val gpio_input_bit_get(GPIOF, GPIO_PIN_14)
#define KEY_DOWN_Val gpio_input_bit_get(GPIOC, GPIO_PIN_13)
#define KEY_LEFT_Val gpio_input_bit_get(GPIOA, GPIO_PIN_0)
#define KEY_RIGHT_Val gpio_input_bit_get(GPIOF, GPIO_PIN_13)
#define KEY_OK_Val gpio_input_bit_get(GPIOF, GPIO_PIN_15)
本次按键更新