]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/pwm.c
mudflap for dual rearlights
[bike-lights.git] / firmware / pwm.c
1 #include <avr/io.h>
2 #include <avr/interrupt.h>
3 #include <util/delay.h>
4
5 #include "lights.h"
6
7 #define PWM_MAX 0x1FF
8
9 void init_pwm()
10 {
11         /* Async clock */
12         PLLCSR = _BV(PLLE);
13
14         /* Synchronize to the phase lock */
15         _delay_ms(1);
16         while ((PLLCSR & _BV(PLOCK)) == 0)
17                 ;
18         PLLCSR |= _BV(PCKE);
19
20         // PWM channel D is inverted, ...
21         TCCR1C = _BV(COM1D1) | _BV(COM1D0) | _BV(PWM1D);
22         // PWM channels A and B are not
23         TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(PWM1A) | _BV(PWM1B);
24         TCCR1D = 0;
25         TCCR1B = _BV(CS10);                     // no clock prescaling
26
27         TC1H = PWM_MAX >> 8;
28         OCR1C = PWM_MAX & 0xFF;                         // TOP value
29
30         TC1H = PWM_MAX >> 8;            // PWM3 is inverted
31         OCR1D = PWM_MAX & 0xFF;
32
33         TC1H = 0x00;
34         OCR1B = OCR1A = 0;              // initial stride is 0
35
36         DDRB  &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // tristate it
37         PORTB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // set to zero
38 }
39
40 void susp_pwm()
41 {
42         DDRB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 ));
43         TCCR1D = TCCR1C = TCCR1B = TCCR1A = 0;
44         TIMSK = 0;
45         TIFR = 0;
46 }
47
48 void pwm_off(unsigned char n)
49 {
50         switch (n) {
51         case 0: DDRB &= ~_BV(PB1); break;
52         case 1: DDRB &= ~_BV(PB3); break;
53         case 2: DDRB &= ~_BV(PB5); break;
54         }
55 }
56
57 void pwm_set(unsigned char n, uint16_t stride)
58 {
59         unsigned char hi, lo;
60
61         if (stride > PWM_MAX)
62                 stride = PWM_MAX;
63
64         if (n == 2)
65                 stride = PWM_MAX - stride;
66
67         hi = stride >> 8;
68         lo = stride & 0xFF;
69
70         switch (n) {
71         case 0:
72                 TC1H = hi;
73                 OCR1A = lo;
74                 DDRB |= _BV(PB1);
75                 break;
76         case 1:
77                 TC1H = hi;
78                 OCR1B = lo;
79                 DDRB |= _BV(PB3);
80                 break;
81         case 2:
82                 TC1H = hi;
83                 OCR1D = lo;
84                 DDRB |= _BV(PB5);
85                 break;
86         }
87 }
88
89 #if 0
90 static void inline pwm_handler()
91 {
92         OCR1A = pwmval[0];
93         OCR1B = pwmval[1];
94         OCR1D = pwmval[2];
95         TIMSK &= ~_BV(TOIE1);
96 }
97
98 ISR(TIMER1_OVF_vect)
99 {
100         pwm_handler();
101 }
102 #endif
103