]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/pwm.c
step-up convertor at PWM 3 working
[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_on(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_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, unsigned char stride)
58 {
59         TC1H = 0x00;
60         switch (n) {
61         case 0: OCR1A = stride; break;
62         case 1: OCR1B = stride; break;
63         case 2: {
64                         uint16_t s16 = PWM_MAX - (uint16_t)stride;
65                         volatile unsigned char hi, lo;
66                         hi = s16 >> 8;
67                         lo = s16 & 0xFF;
68                         TC1H = hi;
69                         OCR1D = lo;
70                 }
71                 break;
72         }
73 }
74
75 #if 0
76 static void inline pwm_handler()
77 {
78         OCR1A = pwmval[0];
79         OCR1B = pwmval[1];
80         OCR1D = pwmval[2];
81         TIMSK &= ~_BV(TOIE1);
82 }
83
84 ISR(TIMER1_OVF_vect)
85 {
86         pwm_handler();
87 }
88 #endif
89