在bsp文件夹中新建key.c和key.h
PB0 PB1 PB2 PA0设置为GPIO_input,模式为上拉
打开TIM
输入频率/(PSC*Counter)=中断频率
设置为1ms的中断
tips:一定要记得开NVIC中断
点击生成代码
将key.c添加到User文件夹
记得在all.h中添加key.h,tim.h头文件
key.c
#include "key.h"struct Bkeys bkey[5] = {0,0};
//low 0
//high 1
uint8_t key_read()
{if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0)==0) return 1;else if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1)==0) return 2;else if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2)==0) return 3;else if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0)==0) return 4;//注意此处别写错else return 0;
}void key_serv()//包含短按和长按
{uint8_t key_sta = key_read(); if(key_sta!=0){bkey[key_sta].age++;if(bkey[key_sta].age == 2) bkey[key_sta].press = 1;}else{for (int i=0;i<5;i++) {if(bkey[i].press==1 && bkey[i].long_flag==0) bkey[i].short_flag = 1;bkey[i].age=0;bkey[i].press=0;bkey[i].long_flag=0;}}if(bkey[key_sta].age>69) bkey[key_sta].long_flag=1;
}
key.h
#ifndef KEY_H
#define KEY_H
#include "all.h"void key_serv(void);
struct Bkeys
{uint8_t age;uint8_t short_flag;uint8_t long_flag;uint8_t press;};#endif
记得在setup里初始化tim6
all.c
#include "all.h"uint8_t led_sta=0x20;//LED初始化参数
extern struct Bkeys bkey[];//按键存储void LED_Disp(uint8_t dsLED)//LED控制
{HAL_GPIO_WritePin(GPIOC,GPIO_PIN_All,GPIO_PIN_SET);//所有LED熄灭HAL_GPIO_WritePin(GPIOC,dsLED<<8,GPIO_PIN_RESET);//左移8位。控制C8~C15引脚,值为1的点亮HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_SET);//开锁存器HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);//关锁存器
}
void LED_Chg(uint8_t num,uint8_t sta)//单独控制一个LED
{uint8_t pos = 0x01<<(num-1);led_sta =(led_sta&(~pos))|(pos*sta);LED_Disp(led_sta);
}void setup()
{HAL_TIM_Base_Start_IT(&htim6);//开启TIMLED_Disp(0x00);}void loop()
{if(bkey[1].short_flag==1){LED_Chg(1,1);bkey[1].short_flag = 0;//用完记得清零}if(bkey[1].long_flag==1){LED_Chg(2,1);}}void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{if(htim->Instance == TIM6)key_serv();}