]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/pwm.c
pwm: 16-bit pwm and adc values
[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 pwm_off(unsigned char n)
41 {
42         switch (n) {
43         case 0: DDRB &= ~_BV(PB1); break;
44         case 1: DDRB &= ~_BV(PB3); break;
45         case 2: DDRB &= ~_BV(PB5); break;
46         }
47 }
48
49 void pwm_set(unsigned char n, uint16_t stride)
50 {
51         unsigned char hi, lo;
52
53         if (stride > PWM_MAX)
54                 stride = PWM_MAX;
55
56         if (n == 2)
57                 stride = PWM_MAX - stride;
58
59         hi = stride >> 8;
60         lo = stride & 0xFF;
61
62         switch (n) {
63         case 0:
64                 TC1H = hi;
65                 OCR1A = lo;
66                 DDRB |= _BV(PB1);
67                 break;
68         case 1:
69                 TC1H = hi;
70                 OCR1B = lo;
71                 DDRB |= _BV(PB3);
72                 break;
73         case 2:
74                 TC1H = hi;
75                 OCR1D = lo;
76                 DDRB |= _BV(PB5);
77                 break;
78         }
79 }
80
81 #if 0
82 static void inline pwm_handler()
83 {
84         OCR1A = pwmval[0];
85         OCR1B = pwmval[1];
86         OCR1D = pwmval[2];
87         TIMSK &= ~_BV(TOIE1);
88 }
89
90 ISR(TIMER1_OVF_vect)
91 {
92         pwm_handler();
93 }
94 #endif
95