]> git.donarmstrong.com Git - tmk_firmware.git/blob - common/timer.c
usb_hid: Fix timer size uint16_t to uint32_t;
[tmk_firmware.git] / common / 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.h"
22
23
24 // counter resolution 1ms
25 volatile uint32_t timer_count = 0;
26
27 void 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
50 inline
51 void timer_clear(void)
52 {
53     uint8_t sreg = SREG;
54     cli();
55     timer_count = 0;
56     SREG = sreg;
57 }
58
59 inline
60 uint16_t timer_read(void)
61 {
62     uint32_t t;
63
64     uint8_t sreg = SREG;
65     cli();
66     t = timer_count;
67     SREG = sreg;
68
69     return (t & 0xFFFF);
70 }
71
72 inline
73 uint32_t timer_read32(void)
74 {
75     uint32_t t;
76
77     uint8_t sreg = SREG;
78     cli();
79     t = timer_count;
80     SREG = sreg;
81
82     return t;
83 }
84
85 inline
86 uint16_t timer_elapsed(uint16_t last)
87 {
88     uint32_t t;
89
90     uint8_t sreg = SREG;
91     cli();
92     t = timer_count;
93     SREG = sreg;
94
95     return TIMER_DIFF_16((t & 0xFFFF), last);
96 }
97
98 inline
99 uint32_t timer_elapsed32(uint32_t last)
100 {
101     uint32_t t;
102
103     uint8_t sreg = SREG;
104     cli();
105     t = timer_count;
106     SREG = sreg;
107
108     return TIMER_DIFF_32(t, last);
109 }
110
111 // excecuted once per 1ms.(excess for just timer count?)
112 ISR(TIMER0_COMPA_vect)
113 {
114     timer_count++;
115 }