stm32按键消抖代码
时间: 2024-06-11 07:02:00 浏览: 18
按键消抖是指在按下或者释放按键时,由于机械原因或者电气原因,按键会产生一些波动,这些波动可能会被识别为多次按键操作。因此,需要对按键进行消抖处理,以确保只识别一次按键操作。
以下是一个基于STM32的简单按键消抖代码:
```c
#define BUTTON_GPIO_PORT GPIOA
#define BUTTON_GPIO_PIN GPIO_Pin_0
void Button_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = BUTTON_GPIO_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(BUTTON_GPIO_PORT, &GPIO_InitStructure);
}
uint8_t Button_Read(void)
{
static uint8_t prevState = 1;
uint8_t currState;
currState = GPIO_ReadInputDataBit(BUTTON_GPIO_PORT, BUTTON_GPIO_PIN);
if(currState == 0 && prevState == 1)
{
Delay_ms(10);
currState = GPIO_ReadInputDataBit(BUTTON_GPIO_PORT, BUTTON_GPIO_PIN);
if(currState == 0)
{
prevState = 0;
return 1;
}
}
else if(currState == 1 && prevState == 0)
{
Delay_ms(10);
currState = GPIO_ReadInputDataBit(BUTTON_GPIO_PORT, BUTTON_GPIO_PIN);
if(currState == 1)
{
prevState = 1;
}
}
return 0;
}
```
该代码使用了STM32的GPIO模块来实现按键读取,并在程序中使用了一个状态机来实现按键消抖。在Button_Read()函数中,首先读取当前按键状态currState,并将其与前一个状态prevState进行比较。如果当前状态是0(按键按下),且前一个状态是1(按键释放),则延时10毫秒,再次读取按键状态currState。如果当前状态还是0,则认为这是一次有效的按键操作,返回1。如果当前状态是1(按键释放),且前一个状态是0(按键按下),则同样延时10毫秒,再次读取按键状态currState,并更新前一个状态prevState。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)