stm32按键中断消抖代码
时间: 2023-09-07 11:11:05 浏览: 228
stm32中断按键
以下是一份STM32按键中断消抖代码示例:
```
#include "stm32f4xx.h"
#define BUTTON_PIN GPIO_Pin_0
#define BUTTON_PORT GPIOA
/* 延时函数 */
void delay(uint32_t time) {
while (time--);
}
/* 按键中断处理函数 */
void EXTI0_IRQHandler(void) {
if (EXTI_GetITStatus(EXTI_Line0) != RESET) {
/* 等待一段时间,检测按键是否仍然被按下 */
delay(10000);
if (GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN) == Bit_RESET) {
/* 按键仍然被按下,执行相应操作 */
/* 清除中断标志位 */
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
}
int main(void) {
/* 初始化按键GPIO口 */
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(BUTTON_PORT, &GPIO_InitStructure);
/* 配置按键中断线 */
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
while (1) {
/* 主程序循环 */
}
}
```
这份代码中,按键引脚被配置为上拉输入,即按键未按下时引脚被拉高。在按键中断处理函数中,我们加入了一个延时函数,等待一段时间后再次检测按键状态,如果按键仍然被按下,则执行相应操作。这样可以有效消除按键的抖动。
阅读全文