timer.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. Copyright 2011 Jun Wako <wakojun@gmail.com>
  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 <util/atomic.h>
  17. #include <stdint.h>
  18. #include "timer_avr.h"
  19. #include "timer.h"
  20. // counter resolution 1ms
  21. // NOTE: union { uint32_t timer32; struct { uint16_t dummy; uint16_t timer16; }}
  22. volatile uint32_t timer_count;
  23. void timer_init(void)
  24. {
  25. // Timer0 CTC mode
  26. TCCR0A = 0x02;
  27. #if TIMER_PRESCALER == 1
  28. TCCR0B = 0x01;
  29. #elif TIMER_PRESCALER == 8
  30. TCCR0B = 0x02;
  31. #elif TIMER_PRESCALER == 64
  32. TCCR0B = 0x03;
  33. #elif TIMER_PRESCALER == 256
  34. TCCR0B = 0x04;
  35. #elif TIMER_PRESCALER == 1024
  36. TCCR0B = 0x05;
  37. #else
  38. # error "Timer prescaler value is NOT vaild."
  39. #endif
  40. OCR0A = TIMER_RAW_TOP;
  41. TIMSK0 = (1<<OCIE0A);
  42. }
  43. inline
  44. void timer_clear(void)
  45. {
  46. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  47. timer_count = 0;
  48. }
  49. }
  50. inline
  51. uint16_t timer_read(void)
  52. {
  53. uint32_t t;
  54. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  55. t = timer_count;
  56. }
  57. return (t & 0xFFFF);
  58. }
  59. inline
  60. uint32_t timer_read32(void)
  61. {
  62. uint32_t t;
  63. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  64. t = timer_count;
  65. }
  66. return t;
  67. }
  68. inline
  69. uint16_t timer_elapsed(uint16_t last)
  70. {
  71. uint32_t t;
  72. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  73. t = timer_count;
  74. }
  75. return TIMER_DIFF_16((t & 0xFFFF), last);
  76. }
  77. inline
  78. uint32_t timer_elapsed32(uint32_t last)
  79. {
  80. uint32_t t;
  81. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
  82. t = timer_count;
  83. }
  84. return TIMER_DIFF_32(t, last);
  85. }
  86. // excecuted once per 1ms.(excess for just timer count?)
  87. ISR(TIMER0_COMPA_vect)
  88. {
  89. timer_count++;
  90. }