root / toolbox / led.c @ dc472500
History | View | Annotate | Download (853 Bytes)
1 | dc472500 | Tom Mullins | #include "led.h" |
---|---|---|---|
2 | #include <avr/io.h> |
||
3 | |||
4 | #define PRESCALE 64 |
||
5 | #define CLOCK_SEL 3 |
||
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 | char count;
|
||
12 | uint16_t period; |
||
13 | |||
14 | uint16_t ms; |
||
15 | uint16_t error; |
||
16 | |||
17 | static void blink() { |
||
18 | count--; |
||
19 | if (count % 2) { |
||
20 | led_yellow(); |
||
21 | } else {
|
||
22 | led_off(); |
||
23 | } |
||
24 | } |
||
25 | |||
26 | ISR(TIMER0_COMPA_vect) { |
||
27 | error += ERROR; |
||
28 | if (error >= 1000) { |
||
29 | error -= 1000;
|
||
30 | } else {
|
||
31 | ms++; |
||
32 | if (ms == period) {
|
||
33 | blink(); |
||
34 | if (count = 0) { |
||
35 | TCCR0B = 0;
|
||
36 | } |
||
37 | ms = 0;
|
||
38 | } |
||
39 | } |
||
40 | } |
||
41 | |||
42 | void led_blink_start(unsigned int period_ms, char n_times) { |
||
43 | led_yellow(); |
||
44 | ms = 0;
|
||
45 | error = 0;
|
||
46 | count = n_times*2-1; |
||
47 | period = period_ms; |
||
48 | OCR0A = OCR; |
||
49 | TCCR0A = _BV(WGM01); |
||
50 | TCCR0B = CLOCK_SEL; |
||
51 | } |
||
52 | |||
53 | char led_blink_done() {
|
||
54 | return count == 0; |
||
55 | } |