-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer0.c
92 lines (77 loc) · 2.07 KB
/
timer0.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* timer0.c
*
* Author: Peter Sutton
*
* We setup timer0 to generate an interrupt every 1ms
* We update a global clock tick variable - whose value
* can be retrieved using the get_clock_ticks() function.
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "timer0.h"
/* Our internal clock tick count - incremented every
* millisecond. Will overflow every ~49 days. */
static volatile uint32_t clockTicks;
uint8_t pause;
/* Set up timer 0 to generate an interrupt every 1ms.
* We will divide the clock by 64 and count up to 124.
* We will therefore get an interrupt every 64 x 125
* clock cycles, i.e. every 1 milliseconds with an 8MHz
* clock.
* The counter will be reset to 0 when it reaches it's
* output compare value.
*/
void init_timer0(void) {
/* Reset clock tick count. L indicates a long (32 bit)
* constant.
*/
clockTicks = 0L;
pause = 0;
/* Clear the timer */
TCNT0 = 0;
/* Set the output compare value to be 124 */
OCR0A = 124;
/* Set the timer to clear on compare match (CTC mode)
* and to divide the clock by 64. This starts the timer
* running.
*/
TCCR0A = (1<<WGM01);
TCCR0B = (1<<CS01)|(1<<CS00);
/* Enable an interrupt on output compare match.
* Note that interrupts have to be enabled globally
* before the interrupts will fire.
*/
TIMSK0 |= (1<<OCIE0A);
/* Make sure the interrupt flag is cleared by writing a
* 1 to it.
*/
TIFR0 &= (1<<OCF0A);
}
uint32_t get_current_time(void) {
uint32_t returnValue;
/* Disable interrupts so we can be sure that the interrupt
* doesn't fire when we've copied just a couple of bytes
* of the value. Interrupts are re-enabled if they were
* enabled at the start.
*/
uint8_t interruptsOn = bit_is_set(SREG, SREG_I);
cli();
returnValue = clockTicks;
if(interruptsOn) {
sei();
}
return returnValue;
}
void pause_timer(uint8_t set) {
pause = set;
if(!pause) {
TIFR0 &= (1<<OCF0A);
}
}
ISR(TIMER0_COMPA_vect) {
/* Increment our clock tick count */
if(!pause) {
clockTicks++;
}
}