Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timer.c 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2011 Jun Wako <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <avr/io.h>
  15. #include <avr/interrupt.h>
  16. #include <stdint.h>
  17. #include "timer.h"
  18. volatile uint16_t timer_count = 0;
  19. // Configure timer 0 to generate a timer overflow interrupt every
  20. // 256*1024 clock cycles, or approx 61 Hz when using 16 MHz clock
  21. // This demonstrates how to use interrupts to implement a simple
  22. // inactivity timeout.
  23. void timer_init(void)
  24. {
  25. TCCR0A = 0x00;
  26. TCCR0B = 0x05;
  27. TIMSK0 = (1<<TOIE0);
  28. }
  29. inline
  30. void timer_clear(void)
  31. {
  32. uint8_t sreg = SREG;
  33. cli();
  34. timer_count = 0;
  35. SREG = sreg;
  36. }
  37. inline
  38. uint16_t timer_read(void)
  39. {
  40. uint16_t t;
  41. uint8_t sreg = SREG;
  42. cli();
  43. t = timer_count;
  44. SREG = sreg;
  45. return t;
  46. }
  47. inline
  48. uint16_t timer_elapsed(uint16_t last)
  49. {
  50. uint16_t t;
  51. uint8_t sreg = SREG;
  52. cli();
  53. t = timer_count;
  54. SREG = sreg;
  55. return TIMER_DIFF(t, last);
  56. }
  57. // This interrupt routine is run approx 61 times per second.
  58. // A very simple inactivity timeout is implemented, where we
  59. // will send a space character and print a message to the
  60. // hid_listen debug message window.
  61. ISR(TIMER0_OVF_vect)
  62. {
  63. timer_count++;
  64. }