按键扫描代码
/*********************************************************************************函数名称:u8 Key_Scan(void)**功能描述:按键检测函数**入口参数:无**返回:按键事件状态**使用本函数的注意点:需要用一个定时中断来定时执行*******************************************************************************/u8 Key_Scan(void){ if (BUTTON_PIN == ACTIVE_LEVEL) { if (Press_Counter >= LONG_COUNT) //长按未松开 { return KEY_STATUS_NO_LOOSEN; } // 计数 Press_Counter++; // 按键按下 while (Press_Counter >= SHORT_COUNT) { //检测到松开、超时的时候,则处理 if ((BUTTON_PIN != ACTIVE_LEVEL) || (Press_Counter >= LONG_COUNT)) { // 长按键 if (Press_Counter >= LONG_COUNT) { return KEY_STATUS_TRIGGER_LONG; } // 短按键 else { return KEY_STATUS_TRIGGER_SHORT; //3s内的按键松开为短按 } } //计数判断长短按 Press_Counter++; delay_ms(1); } } else { Press_Counter = 0; //计数清零 } return KEY_STATUS_IDLE;}
定时执行代码(示例)
INTERRUPT_HANDLER(TIM4_UPD_OVF_IRQHandler, 25){ /* In order to detect unexpected events during development, it is recommended to set a breakpoint on the following instruction. */ switch (Key_Function) { //空闲 case KEY_STATUS_IDLE: { //检测按键当前状态 Ret = Key_Scan(); //短按键触发时 if (Ret == KEY_STATUS_TRIGGER_SHORT) { Key_Function = KEY_SHORT_EVENT; } //长按键触发时 else if (Ret == KEY_STATUS_TRIGGER_LONG) { Key_Function = KEY_LONG_EVENT; } break; } //短按键处理 case KEY_SHORT_EVENT: { LED_Fast_Flash(); // do something //返回空闲状态 Key_Function = IDLE_EVENT; TIM4_Cmd(DISABLE); break; } //长按键处理 case KEY_LONG_EVENT: { LED_Slow_Flash(); // do something //返回空闲状态 Key_Function = IDLE_EVENT; TIM4_Cmd(DISABLE); break; } //其他 default: { //返回空闲状态 Key_Function = IDLE_EVENT; // TIM4_Cmd(DISABLE); break; } } /* 清除中断标志位 */ TIM4_ClearITPendingBit(TIM4_IT_Update);}