]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/pwm.c
firmware source moved into subdirectory
[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 void init_pwm()
8 {
9         /* Async clock */
10         PLLCSR = _BV(PLLE);
11
12         /* Synchronize to the phase lock */
13         _delay_ms(1);
14         while ((PLLCSR & _BV(PLOCK)) == 0)
15                 ;
16         PLLCSR |= _BV(PCKE);
17
18         TCCR1C = _BV(COM1D0) | _BV(COM1D1) | _BV(PWM1D);
19         TCCR1A = _BV(COM1A0) | _BV(COM1A1) | _BV(COM1B0) | _BV(COM1B1) | _BV(PWM1A) | _BV(PWM1B);
20         TCCR1B = _BV(7)                         // PWM1X: PWM inversion mode
21                 | _BV(CS10)                     // no clock prescaling
22                 ;
23         TC1H = 0x01;
24         OCR1C = 0xFF;                           // TOP value
25
26         TC1H = 0x00;
27         OCR1D = OCR1B = OCR1A = 0;              // initial stride is 0
28
29         DDRB  &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // tristate it
30         PORTB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // set to zero
31 }
32
33 void pwm_on(unsigned char n)
34 {
35         switch (n) {
36         case 0: DDRB |= _BV(PB1); break;
37         case 1: DDRB |= _BV(PB3); break;
38         case 2: DDRB |= _BV(PB5); break;
39         }
40 }
41
42 void pwm_off(unsigned char n)
43 {
44         switch (n) {
45         case 0: DDRB &= ~_BV(PB1); break;
46         case 1: DDRB &= ~_BV(PB3); break;
47         case 2: DDRB &= ~_BV(PB5); break;
48         }
49 }
50
51 void pwm_set(unsigned char n, unsigned char stride)
52 {
53         TC1H = 0x00;
54         switch (n) {
55         case 0: OCR1A = stride; break;
56         case 1: OCR1B = stride; break;
57         case 2: OCR1D = stride; break;
58         }
59 }
60
61 #if 0
62 static void inline pwm_handler()
63 {
64         OCR1A = pwmval[0];
65         OCR1B = pwmval[1];
66         OCR1D = pwmval[2];
67         TIMSK &= ~_BV(TOIE1);
68 }
69
70 ISR(TIMER1_OVF_vect)
71 {
72         pwm_handler();
73 }
74 #endif
75