按键扫描代码

  1. /*******************************************************************************
  2. **函数名称:u8 Key_Scan(void)
  3. **功能描述:按键检测函数
  4. **入口参数:无
  5. **返回:按键事件状态
  6. **使用本函数的注意点:需要用一个定时中断来定时执行
  7. *******************************************************************************/
  8. u8 Key_Scan(void)
  9. {
  10. if (BUTTON_PIN == ACTIVE_LEVEL)
  11. {
  12. if (Press_Counter >= LONG_COUNT) //长按未松开
  13. {
  14. return KEY_STATUS_NO_LOOSEN;
  15. }
  16. // 计数
  17. Press_Counter++;
  18. // 按键按下
  19. while (Press_Counter >= SHORT_COUNT)
  20. {
  21. //检测到松开、超时的时候,则处理
  22. if ((BUTTON_PIN != ACTIVE_LEVEL) || (Press_Counter >= LONG_COUNT))
  23. {
  24. // 长按键
  25. if (Press_Counter >= LONG_COUNT)
  26. {
  27. return KEY_STATUS_TRIGGER_LONG;
  28. }
  29. // 短按键
  30. else
  31. {
  32. return KEY_STATUS_TRIGGER_SHORT; //3s内的按键松开为短按
  33. }
  34. }
  35. //计数判断长短按
  36. Press_Counter++;
  37. delay_ms(1);
  38. }
  39. }
  40. else
  41. {
  42. Press_Counter = 0; //计数清零
  43. }
  44. return KEY_STATUS_IDLE;
  45. }

定时执行代码(示例)

  1. INTERRUPT_HANDLER(TIM4_UPD_OVF_IRQHandler, 25)
  2. {
  3. /* In order to detect unexpected events during development,
  4. it is recommended to set a breakpoint on the following instruction.
  5. */
  6. switch (Key_Function)
  7. {
  8. //空闲
  9. case KEY_STATUS_IDLE:
  10. {
  11. //检测按键当前状态
  12. Ret = Key_Scan();
  13. //短按键触发时
  14. if (Ret == KEY_STATUS_TRIGGER_SHORT)
  15. {
  16. Key_Function = KEY_SHORT_EVENT;
  17. }
  18. //长按键触发时
  19. else if (Ret == KEY_STATUS_TRIGGER_LONG)
  20. {
  21. Key_Function = KEY_LONG_EVENT;
  22. }
  23. break;
  24. }
  25. //短按键处理
  26. case KEY_SHORT_EVENT:
  27. {
  28. LED_Fast_Flash();
  29. // do something
  30. //返回空闲状态
  31. Key_Function = IDLE_EVENT;
  32. TIM4_Cmd(DISABLE);
  33. break;
  34. }
  35. //长按键处理
  36. case KEY_LONG_EVENT:
  37. {
  38. LED_Slow_Flash();
  39. // do something
  40. //返回空闲状态
  41. Key_Function = IDLE_EVENT;
  42. TIM4_Cmd(DISABLE);
  43. break;
  44. }
  45. //其他
  46. default:
  47. {
  48. //返回空闲状态
  49. Key_Function = IDLE_EVENT;
  50. // TIM4_Cmd(DISABLE);
  51. break;
  52. }
  53. }
  54. /* 清除中断标志位 */
  55. TIM4_ClearITPendingBit(TIM4_IT_Update);
  56. }