aboutsummaryrefslogtreecommitdiff
path: root/common/timer.c
diff options
context:
space:
mode:
Diffstat (limited to 'common/timer.c')
-rw-r--r--common/timer.c89
1 files changed, 89 insertions, 0 deletions
diff --git a/common/timer.c b/common/timer.c
new file mode 100644
index 000000000..48a38c9b6
--- /dev/null
+++ b/common/timer.c
@@ -0,0 +1,89 @@
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.h"
22
23
24// counter resolution 1ms
25volatile uint16_t timer_count = 0;
26
27void timer_init(void)
28{
29 // Timer0 CTC mode
30 TCCR0A = 0x02;
31
32#if TIMER_PRESCALER == 1
33 TCCR0B = 0x01;
34#elif TIMER_PRESCALER == 8
35 TCCR0B = 0x02;
36#elif TIMER_PRESCALER == 64
37 TCCR0B = 0x03;
38#elif TIMER_PRESCALER == 256
39 TCCR0B = 0x04;
40#elif TIMER_PRESCALER == 1024
41 TCCR0B = 0x05;
42#else
43# error "Timer prescaler value is NOT vaild."
44#endif
45
46 OCR0A = TIMER_RAW_TOP;
47 TIMSK0 = (1<<OCIE0A);
48}
49
50inline
51void timer_clear(void)
52{
53 uint8_t sreg = SREG;
54 cli();
55 timer_count = 0;
56 SREG = sreg;
57}
58
59inline
60uint16_t timer_read(void)
61{
62 uint16_t t;
63
64 uint8_t sreg = SREG;
65 cli();
66 t = timer_count;
67 SREG = sreg;
68
69 return t;
70}
71
72inline
73uint16_t timer_elapsed(uint16_t last)
74{
75 uint16_t t;
76
77 uint8_t sreg = SREG;
78 cli();
79 t = timer_count;
80 SREG = sreg;
81
82 return TIMER_DIFF_MS(t, last);
83}
84
85// excecuted once per 1ms.(excess for just timer count?)
86ISR(TIMER0_COMPA_vect)
87{
88 timer_count++;
89}