Project

General

Profile

Statistics
| Branch: | Revision:

root / toolbox / time.c @ 975af07c

History | View | Annotate | Download (639 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 volatile char ready;
11
static char ms;
12
static uint16_t error;
13

    
14
ISR(TIMER0_COMPA_vect) {
15
  error += ERROR;
16
  if (error >= 1000) {
17
    error -= 1000;
18
    OCR0A = OCR+1;
19
  } else {
20
    OCR0A = OCR;
21
  }
22
  if (++ms == TICK_MS) {
23
    ready = 1;
24
    ms = 0;
25
  }
26
}
27

    
28
void time_init() {
29
  OCR0A = OCR;
30
  TIMSK = _BV(OCIE0A);
31
  TCCR0A = _BV(WGM01);
32
  TCCR0B = CLOCK_SEL;
33
}
34

    
35
void time_wait() {
36
  while (!ready);
37
  ready = 0;
38
}