-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.c
74 lines (57 loc) · 1.51 KB
/
timer.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
/*
* "THE BEER-WARE LICENSE" (Revision 42):
* Martin Wenger <[email protected]> and Stefan Rupp <[email protected]>
* wrote this file. As long as you retain this notice you can do whatever you want
* with this stuff. If we meet some day, and you think this stuff is worth it,
* you can buy me/us a beer in return.
* (c) 2005-2007 Martin Wenger, Stefan Rupp. Daniel Steuer
*/
#include <stdint.h>
#include <avr/io.h>
#include <util/atomic.h>
#include <avr/interrupt.h>
#include "timer.h"
/* TimerTime gets increased on every SIG_OUTPUT_COMPARE2 interrupt
* those interrupts happen every 1ms
*/
static volatile uint32_t timer_time;
ISR(TIMER0_COMPA_vect) {
++timer_time;
return;
}
/**
* Initialize the timer
* This function has to be called first, before calling TimerWait and/or TimerGet,
* else TimerGet will always return 0, and TimerWait will wait forever!
*/
void timer_init(void) {
// Reset timer to zero
timer_time = 0;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
// timebase: 1000 Hz
TCCR0A = (1<<WGM01);
TCCR0B = (1<<CS01)|(1<<CS00);
OCR0A = 249;
TIMSK0 |= (1<<OCIE0A);
}
}
/**
* Get the current time
* \return the current time (in ms)
*/
uint32_t timer_getMs(void) {
uint32_t result;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
result = timer_time;
}
return result;
}
/**
* Wait for (at least) the specified amount of time
* \param delay The time to wait (in ms)
*/
void timer_wait(uint32_t delay) {
uint32_t end = timer_getMs() + delay +1;
while ( end > timer_getMs() );
return;
}