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