root / toolbox / time.c @ 94548bf4
History | View | Annotate | Download (618 Bytes)
1 |
#include <stdint.h> |
---|---|
2 |
#include <avr/io.h> |
3 |
#include <avr/interrupt.h> |
4 |
#include "time.h" |
5 |
|
6 |
/* F_CPU / PRESCALE = OCR * 1000 + ERROR */
|
7 |
#define OCR (F_CPU / PRESCALE / 1000UL) |
8 |
#define ERROR (F_CPU / PRESCALE - OCR * 1000UL) |
9 |
|
10 |
static char ready, ms; |
11 |
static uint16_t error;
|
12 |
|
13 |
ISR(TIMER0_COMPA_vect) { |
14 |
error += ERROR; |
15 |
if (error >= 1000) { |
16 |
error -= 1000;
|
17 |
OCR0A = OCR+1;
|
18 |
} else {
|
19 |
OCR0A = OCR; |
20 |
} |
21 |
if (++ms == TICK_MS) {
|
22 |
ready = 1;
|
23 |
ms = 0;
|
24 |
} |
25 |
} |
26 |
|
27 |
void time_init() {
|
28 |
OCR0A = OCR; |
29 |
TIMSK = _BV(OCIE0A); |
30 |
TCCR0A = _BV(WGM01); |
31 |
TCCR0B = CLOCK_SEL; |
32 |
} |
33 |
|
34 |
void time_wait() {
|
35 |
while (!ready);
|
36 |
ready = 0;
|
37 |
} |