项目作者: m-xor

项目描述 :
Button debouncer
高级语言: C
项目地址: git://github.com/m-xor/button-for-microcontrollers.git
创建时间: 2021-02-03T13:08:27Z
项目社区:https://github.com/m-xor/button-for-microcontrollers

开源协议:

下载


To use:

  • define include path to appriopriate port file “button_port.h”
  • define include path to appriopriate config file “button_config.h”
  • define global (or local) variable of Button type and export variable to every file timer is in use (if applicable).
  • include button.h file in every file timer is in use.
  • invoke Button_service in fixed intervals. If called from within interrupt service routine be aware that callbacks’ll be runnging in interrupt context.

Usage example

ATmega328p

  1. /* main.c */
  2. #include <avr/io.h>
  3. #include <avr/interrupt.h>
  4. #include "timer.h"
  5. #include "software_timer.h"
  6. #include "button.h"
  7. #define BUTTON_PERIOD_MS 20
  8. #define LED_BLINK 250
  9. Timer buttonPoll;
  10. Timer ledBlink;
  11. Button btns;
  12. void press(ButtonPort mask);
  13. void release(ButtonPort mask);
  14. void led_init(void);
  15. void led_toggle(void);
  16. void led_off(void);
  17. int main() __attribute__((OS_main));
  18. int main()
  19. {
  20. timer_init();
  21. led_init();
  22. Timer_ctor(&buttonPoll);
  23. Timer_setPeriod(&buttonPoll, TICKS(BUTTON_PERIOD_MS,HARDWARE_TICK_MS));
  24. Timer_ctor(&ledBlink);
  25. Timer_setPeriod(&ledBlink, TICKS(LED_BLINK, HARDWARE_TICK_MS));
  26. /* pull ups on inputs */
  27. Button_initInputs();
  28. /* Button class constructor */
  29. Button_ctor(&btns,press,release);
  30. sei();
  31. while(1)
  32. {
  33. /* called every BUTTON_PERIOD_MS milliseconds */
  34. if(Timer_isTime(&buttonPoll)) {
  35. Button_service(&btns);
  36. Timer_setPeriod(&buttonPoll, TICKS(BUTTON_PERIOD_MS,HARDWARE_TICK_MS));
  37. }
  38. if(Timer_isTime(&ledBlink)) {
  39. led_toggle();
  40. Timer_setPeriod(&ledBlink, TICKS(LED_BLINK, HARDWARE_TICK_MS));
  41. }
  42. }
  43. }
  44. void press(ButtonPort mask)
  45. {
  46. /* use mask parameter to identify which button was just pressed */
  47. Timer_activate(&ledBlink,0);
  48. led_off();
  49. }
  50. void release(ButtonPort mask)
  51. {
  52. /* if needed use mask parameter to identify which button was just released */
  53. Timer_activate(&ledBlink,1);
  54. }
  55. void led_init(void)
  56. {
  57. DDRB = _BV(5);
  58. }
  59. void led_toggle(void)
  60. {
  61. PINB = _BV(5);
  62. }
  63. void led_off(void)
  64. {
  65. PORTB &= ~_BV(5);
  66. }
  67. /* timer.h */
  68. #define HARDWARE_TICK_MS 4
  69. /* timer.c */
  70. #include <avr/io.h>
  71. #include <avr/interrupt.h>
  72. #include "software_timer.h"
  73. Timer buttonPoll;
  74. Timer ledBlink;
  75. void timer_init(void)
  76. {
  77. TIMSK0 = _BV(TOIE0);
  78. TCCR0B = _BV(CS02);
  79. }
  80. ISR(TIMER0_OVF_vect)
  81. {
  82. Timer_count(&buttonPoll);
  83. Timer_count(&ledBlink);
  84. }