c
// 1. GPIO初始化(上拉输入)
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP; // 根据按键电路选择上拉或下拉
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// 2. 外部中断配置(下降沿触发)
EXTI_InitTypeDef EXTI_InitStruct = {0};
EXTI_InitStruct.Line = EXTI_LINE_0;
EXTI_InitStruct.Mode = EXTI_MODE_INTERRUPT;
EXTI_InitStruct.Trigger = EXTI_TRIGGER_FALLING;
EXTI_InitStruct.GPIO_Pin = GPIO_PIN_0;
HAL_EXTI_Init(&EXTI_InitStruct);
// 3. NVIC配置(优先级2,子优先级1)
HAL_NVIC_SetPriority(EXTI0_IRQn, 2, 1);
HAL_NVIC_EnableIRQ(EXTI0_IRQn);
// 4. 中断回调函数(状态机防抖)
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
static uint8_t debounce_count = 0;
if (GPIO_Pin == GPIO_PIN_0) {
if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_RESET) {
debounce_count++;
if (debounce_count >= 3) { // 连续3次检测到低电平
debounce_count = 0;
// 执行按键处理逻辑
}
} else {
debounce_count = 0;
}
}
} |
|