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