stm32 按键消抖代码
时间: 2023-03-26 12:03:58 浏览: 188
按键消抖代码
可以使用延时和状态机的方法来实现按键消抖,具体实现可以参考以下代码:
#include "stm32f10x.h"
#define KEY_ON
#define KEY_OFF 1
#define KEY_STATE_IDLE
#define KEY_STATE_PRESS 1
#define KEY_STATE_RELEASE 2
#define KEY_DEBOUNCE_TIME 20 // 消抖时间,单位为毫秒
void key_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
uint8_t key_scan(void)
{
static uint8_t key_state = KEY_STATE_IDLE;
static uint32_t key_press_time = ;
uint8_t key_value = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_);
switch (key_state)
{
case KEY_STATE_IDLE:
if (key_value == KEY_ON)
{
key_state = KEY_STATE_PRESS;
key_press_time = HAL_GetTick();
}
break;
case KEY_STATE_PRESS:
if (key_value == KEY_OFF)
{
key_state = KEY_STATE_IDLE;
}
else if (HAL_GetTick() - key_press_time >= KEY_DEBOUNCE_TIME)
{
key_state = KEY_STATE_RELEASE;
}
break;
case KEY_STATE_RELEASE:
if (key_value == KEY_OFF)
{
key_state = KEY_STATE_IDLE;
return 1;
}
break;
default:
break;
}
return ;
}
int main(void)
{
key_init();
while (1)
{
if (key_scan())
{
// 按键被按下
}
}
}
阅读全文