Revision 94548bf4 toolbox/led.c

View differences:

toolbox/led.c
1 1
#include "led.h"
2
#include <avr/io.h>
3
#include <avr/interrupt.h>
4

  
5
#define PRESCALE 64
6
#define CLOCK_SEL 3
7

  
8
/* F_CPU / PRESCALE = OCR * 1000 + ERROR */
9
#define OCR (F_CPU / PRESCALE / 1000UL)
10
#define ERROR (F_CPU / PRESCALE - OCR * 1000UL)
2
#include "time.h"
11 3

  
12 4
char blink_count;
13 5
enum color_t blink_color;
14
uint16_t blink_period;
15

  
16
uint16_t ms;
17
uint16_t error;
6
uint16_t blink_period, blink_ticks;
18 7

  
19 8
static void led_color(enum color_t color) {
20 9
  switch (color) {
......
33 22
  }
34 23
}
35 24

  
36
static void blink() {
37
  blink_count--;
38
  if (blink_count % 2) {
39
    led_color(blink_color);
40
  } else {
41
    led_off();
42
  }
43
}
44

  
45
ISR(TIMER0_COMPA_vect) {
46
  error += ERROR;
47
  if (error >= 1000) {
48
    error -= 1000;
49
    OCR0A = OCR+1;
50
  } else {
51
    OCR0A = OCR;
52
  }
53
  ms++;
54
  if (ms == blink_period) {
55
    blink();
56
    if (blink_count == 0) {
57
      TCCR0B = 0;
25
void led_tick() {
26
  if (blink_count) {
27
    if (++blink_ticks >= blink_period) {
28
      blink_ticks = 0;
29
      if (--blink_count % 2) {
30
        led_color(blink_color);
31
      } else {
32
        led_off();
33
      }
58 34
    }
59
    ms = 0;
60 35
  }
61 36
}
62 37

  
63 38
void led_blink_start(unsigned int period_ms, char n_times, enum color_t color) {
64

  
65
  ms = 0;
66
  error = 0;
67

  
68 39
  blink_count = n_times*2-1;
69
  blink_period = period_ms/2;
40
  blink_period = period_ms/2/TICK_MS;
41
  blink_ticks = 0;
70 42
  blink_color = color;
71 43
  led_color(color);
72

  
73
  OCR0A = OCR;
74
  TIMSK = _BV(OCIE0A);
75
  TCCR0A = _BV(WGM01);
76
  TCCR0B = CLOCK_SEL;
77

  
78 44
}
79 45

  
80 46
char led_blink_done() {

Also available in: Unified diff