STM32单片机按键检测长按短按状态机编程

本例程使用STM32F103ZET6核心板实验,建议拷贝到串口实验下做测试,有问题欢迎在评论区讨论。

下面是关键代码,遇报错记得包含相应的头文件,请根据自己的板子的实际引脚修改相应的宏定义。

key.h

#define KEY0  GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)//读取按键0
typedef enum
{
          
   
	KEY_UP=1,
	KEY_DOWN,
	KEY_RELEASE,
}key_sta;
uint16_t key_scan(void);

key.c

/*状态机按键检测*/
uint16_t key_scan()
{
          
   
	static uint8_t status=KEY_UP;
	static uint16_t count=0;
//	delay_ms(10);
	switch(status)
	{
          
   
		case KEY_UP:
			if(KEY0==1)
			{
          
   
				count=0;
				status=KEY_DOWN;
			}
			break;
		case KEY_DOWN:
			if(KEY0==1)
			{
          
   
				count++;
			}
			else
			{
          
   
				status=KEY_RELEASE;
			}
			break;
		case KEY_RELEASE:
			status=KEY_UP;
			printf("count=%d
",count);/*打印按下时间: count*10ms 自己根据实际情况做短按长按判定 */
			break;
	}
	return 0;
}
经验分享 程序员 微信小程序 职场和发展