]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/pwm.c
delete pwm_off(), use pwm_set instead
[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 0x0FF
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         TC1H = PWM_MAX >> 8;
27         OCR1C = PWM_MAX & 0xFF;                         // TOP value
28
29         TC1H = PWM_MAX >> 8;
30         OCR1D = PWM_MAX & 0xFF;
31
32         TC1H = 0x00;
33         OCR1B = OCR1A = 0;              // initial stride is 0
34
35         DDRB  &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // tristate it
36         PORTB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // set to zero
37 }
38
39 void pwm_off(unsigned char n)
40 {
41         switch (n) {
42         case 0: DDRB &= ~_BV(PB1); break;
43         case 1: DDRB &= ~_BV(PB3); break;
44         case 2: DDRB &= ~_BV(PB5); break;
45         }
46 }
47
48 void pwm_set(unsigned char n, unsigned char stride)
49 {
50         TC1H = 0x00;
51         switch (n) {
52         case 0:
53                 OCR1A = stride;
54                 DDRB |= _BV(PB1);
55                 break;
56         case 1: OCR1B = stride;
57                 DDRB |= _BV(PB3);
58                 break;
59         case 2: {
60                         uint16_t s16 = PWM_MAX - (uint16_t)stride;
61                         volatile unsigned char hi, lo;
62                         hi = s16 >> 8;
63                         lo = s16 & 0xFF;
64                         TC1H = hi;
65                         OCR1D = lo;
66                         DDRB |= _BV(PB5);
67                 }
68                 break;
69         }
70 }
71
72 #if 0
73 static void inline pwm_handler()
74 {
75         OCR1A = pwmval[0];
76         OCR1B = pwmval[1];
77         OCR1D = pwmval[2];
78         TIMSK &= ~_BV(TOIE1);
79 }
80
81 ISR(TIMER1_OVF_vect)
82 {
83         pwm_handler();
84 }
85 #endif
86