]> git.donarmstrong.com Git - tmk_firmware.git/blob - common/timer.c
Add option 7bit data to serial_soft.c
[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 // NOTE: union { uint32_t timer32; struct { uint16_t dummy; uint16_t timer16; }}
26 volatile uint32_t timer_count = 0;
27
28 void timer_init(void)
29 {
30     // Timer0 CTC mode
31     TCCR0A = 0x02;
32
33 #if TIMER_PRESCALER == 1
34     TCCR0B = 0x01;
35 #elif TIMER_PRESCALER == 8
36     TCCR0B = 0x02;
37 #elif TIMER_PRESCALER == 64
38     TCCR0B = 0x03;
39 #elif TIMER_PRESCALER == 256
40     TCCR0B = 0x04;
41 #elif TIMER_PRESCALER == 1024
42     TCCR0B = 0x05;
43 #else
44 #   error "Timer prescaler value is NOT vaild."
45 #endif
46
47     OCR0A = TIMER_RAW_TOP;
48     TIMSK0 = (1<<OCIE0A);
49 }
50
51 inline
52 void timer_clear(void)
53 {
54     uint8_t sreg = SREG;
55     cli();
56     timer_count = 0;
57     SREG = sreg;
58 }
59
60 inline
61 uint16_t timer_read(void)
62 {
63     uint32_t t;
64
65     uint8_t sreg = SREG;
66     cli();
67     t = timer_count;
68     SREG = sreg;
69
70     return (t & 0xFFFF);
71 }
72
73 inline
74 uint32_t timer_read32(void)
75 {
76     uint32_t t;
77
78     uint8_t sreg = SREG;
79     cli();
80     t = timer_count;
81     SREG = sreg;
82
83     return t;
84 }
85
86 inline
87 uint16_t timer_elapsed(uint16_t last)
88 {
89     uint32_t t;
90
91     uint8_t sreg = SREG;
92     cli();
93     t = timer_count;
94     SREG = sreg;
95
96     return TIMER_DIFF_16((t & 0xFFFF), last);
97 }
98
99 inline
100 uint32_t timer_elapsed32(uint32_t last)
101 {
102     uint32_t t;
103
104     uint8_t sreg = SREG;
105     cli();
106     t = timer_count;
107     SREG = sreg;
108
109     return TIMER_DIFF_32(t, last);
110 }
111
112 // excecuted once per 1ms.(excess for just timer count?)
113 ISR(TIMER0_COMPA_vect)
114 {
115     timer_count++;
116 }