]> git.gir.st - tmk_keyboard.git/blob - tmk_core/common/avr/timer.c
core: Fix for ATtiny85
[tmk_keyboard.git] / tmk_core / common / avr / timer.c
1 /*
2 Copyright 2011 Jun Wako <wakojun@gmail.com>
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along 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; }}
27 volatile uint32_t timer_count = 0;
28
29 void 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 #ifdef TIMSK0
50 TIMSK0 = (1<<OCIE0A);
51 #else
52 TIMSK = (1<<OCIE0A);
53 #endif
54 }
55
56 inline
57 void timer_clear(void)
58 {
59 uint8_t sreg = SREG;
60 cli();
61 timer_count = 0;
62 SREG = sreg;
63 }
64
65 inline
66 uint16_t timer_read(void)
67 {
68 uint32_t t;
69
70 uint8_t sreg = SREG;
71 cli();
72 t = timer_count;
73 SREG = sreg;
74
75 return (t & 0xFFFF);
76 }
77
78 inline
79 uint32_t timer_read32(void)
80 {
81 uint32_t t;
82
83 uint8_t sreg = SREG;
84 cli();
85 t = timer_count;
86 SREG = sreg;
87
88 return t;
89 }
90
91 inline
92 uint16_t timer_elapsed(uint16_t last)
93 {
94 uint32_t t;
95
96 uint8_t sreg = SREG;
97 cli();
98 t = timer_count;
99 SREG = sreg;
100
101 return TIMER_DIFF_16((t & 0xFFFF), last);
102 }
103
104 inline
105 uint32_t timer_elapsed32(uint32_t last)
106 {
107 uint32_t t;
108
109 uint8_t sreg = SREG;
110 cli();
111 t = timer_count;
112 SREG = sreg;
113
114 return TIMER_DIFF_32(t, last);
115 }
116
117 // excecuted once per 1ms.(excess for just timer count?)
118 ISR(TIMER0_COMPA_vect)
119 {
120 timer_count++;
121 }
Imprint / Impressum