aboutsummaryrefslogtreecommitdiff
path: root/tmk_core/common/avr/timer.c
diff options
context:
space:
mode:
Diffstat (limited to 'tmk_core/common/avr/timer.c')
-rw-r--r--tmk_core/common/avr/timer.c117
1 files changed, 117 insertions, 0 deletions
diff --git a/tmk_core/common/avr/timer.c b/tmk_core/common/avr/timer.c
new file mode 100644
index 000000000..292b41c3a
--- /dev/null
+++ b/tmk_core/common/avr/timer.c
@@ -0,0 +1,117 @@
1/*
2Copyright 2011 Jun Wako <wakojun@gmail.com>
3
4This program is free software: you can redistribute it and/or modify
5it under the terms of the GNU General Public License as published by
6the Free Software Foundation, either version 2 of the License, or
7(at your option) any later version.
8
9This program is distributed in the hope that it will be useful,
10but WITHOUT ANY WARRANTY; without even the implied warranty of
11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12GNU General Public License for more details.
13
14You should have received a copy of the GNU General Public License
15along with this program. If not, see <http://www.gnu.org/licenses/>.
16*/
17
18#include <avr/io.h>
19#include <avr/interrupt.h>
20#include <stdint.h>
21#include "timer_avr.h"
22#include "timer.h"
23
24
25// counter resolution 1ms
26// NOTE: union { uint32_t timer32; struct { uint16_t dummy; uint16_t timer16; }}
27volatile uint32_t timer_count = 0;
28
29void timer_init(void)
30{
31 // Timer0 CTC mode
32 TCCR0A = 0x02;
33
34#if TIMER_PRESCALER == 1
35 TCCR0B = 0x01;
36#elif TIMER_PRESCALER == 8
37 TCCR0B = 0x02;
38#elif TIMER_PRESCALER == 64
39 TCCR0B = 0x03;
40#elif TIMER_PRESCALER == 256
41 TCCR0B = 0x04;
42#elif TIMER_PRESCALER == 1024
43 TCCR0B = 0x05;
44#else
45# error "Timer prescaler value is NOT vaild."
46#endif
47
48 OCR0A = TIMER_RAW_TOP;
49 TIMSK0 = (1<<OCIE0A);
50}
51
52inline
53void timer_clear(void)
54{
55 uint8_t sreg = SREG;
56 cli();
57 timer_count = 0;
58 SREG = sreg;
59}
60
61inline
62uint16_t timer_read(void)
63{
64 uint32_t t;
65
66 uint8_t sreg = SREG;
67 cli();
68 t = timer_count;
69 SREG = sreg;
70
71 return (t & 0xFFFF);
72}
73
74inline
75uint32_t timer_read32(void)
76{
77 uint32_t t;
78
79 uint8_t sreg = SREG;
80 cli();
81 t = timer_count;
82 SREG = sreg;
83
84 return t;
85}
86
87inline
88uint16_t timer_elapsed(uint16_t last)
89{
90 uint32_t t;
91
92 uint8_t sreg = SREG;
93 cli();
94 t = timer_count;
95 SREG = sreg;
96
97 return TIMER_DIFF_16((t & 0xFFFF), last);
98}
99
100inline
101uint32_t timer_elapsed32(uint32_t last)
102{
103 uint32_t t;
104
105 uint8_t sreg = SREG;
106 cli();
107 t = timer_count;
108 SREG = sreg;
109
110 return TIMER_DIFF_32(t, last);
111}
112
113// excecuted once per 1ms.(excess for just timer count?)
114ISR(TIMER0_COMPA_vect)
115{
116 timer_count++;
117}