buttons.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <ch.h>
  2. #include <hal.h>
  3. #include "buttons.h"
  4. static btn_hndlr btnh[Button_Num];
  5. /* Constants */
  6. static const ioline_t button_Lines[Button_Num] = {
  7. LINE_BTN_1, LINE_BTN_2, LINE_BTN_3, LINE_BTN_4
  8. }; /* from board.h */
  9. /* Variables */
  10. static binary_semaphore_t btn_bsem;
  11. static virtual_timer_t button_vt;
  12. static button_state_t button_States[Button_Num] = {0};
  13. static uint8_t button_Time[Button_Num] = {0};
  14. /* Functions */
  15. static void button_Process(virtual_timer_t *vtp, void *p) {
  16. (void)vtp;
  17. (void)p;
  18. /* Entering I-Locked state and signaling the semaphore.*/
  19. chSysLockFromISR();
  20. chBSemSignalI(&btn_bsem);
  21. chSysUnlockFromISR();
  22. }
  23. /*
  24. * BTN serving thread.
  25. */
  26. static THD_WORKING_AREA(waBTNThread, 256);
  27. static THD_FUNCTION(BTNThread, arg) {
  28. (void)arg;
  29. static int pause = 0;
  30. while (true) {
  31. /* Waiting for an binary semaphore. */
  32. chBSemWait(&btn_bsem);
  33. if (pause != 0) {
  34. pause --;
  35. } else {
  36. int i;
  37. for (i=0; i<Button_Num; i++) {
  38. if (palReadLine(button_Lines[(button_num_t)i]) == BUTTON_PRESSED) {
  39. /* button pressed */
  40. button_Time[i] ++;
  41. if (button_Time[i] >= BTN_TIME_HOLDED) {
  42. /* process long press */
  43. button_Time[i] -= BTN_TIME_REPEATED;
  44. button_States[i] = BTN_st_Holded;
  45. btnh[i](BTN_st_Pressed); // autorepeat
  46. }
  47. } else if (button_Time[i] != 0) {
  48. /* button released */
  49. if (button_Time[i] >= BTN_TIME_PRESSED) {
  50. /* process short press */
  51. button_States[i] = BTN_st_Pressed;
  52. btnh[i](BTN_st_Pressed);
  53. }
  54. button_Time[i] = 0;
  55. button_States[i] = BTN_st_Released;
  56. pause = BTN_SCAN_PAUSE;
  57. //btnh[i](BTN_st_Released);
  58. }
  59. } /* end FOR */
  60. } /* end Pause check */
  61. } /* end WHILE */
  62. }
  63. void buttons_Init(btn_hndlr ha[]) {
  64. btnh[Button1] = ha[Button1];
  65. btnh[Button2] = ha[Button2];
  66. btnh[Button3] = ha[Button3];
  67. btnh[Button4] = ha[Button4];
  68. /* Initializing the Button semaphore in the "taken" state. */
  69. chBSemObjectInit(&btn_bsem, true);
  70. /* Starting the Button thread. */
  71. chThdCreateStatic(waBTNThread, sizeof(waBTNThread), NORMALPRIO, BTNThread, NULL);
  72. /* Starting a virtual timer ticking the thread. */
  73. chVTSetContinuous(&button_vt, TIME_MS2I(BTN_SCAN_PERIOD), button_Process, NULL);
  74. }
  75. button_state_t buttons_GetState(const button_num_t btn) {
  76. return button_States[btn];
  77. }