]> www.fi.muni.cz Git - bike-lights.git/blob - pwm.c
gpio.c: gpio leds and other tools
[bike-lights.git] / 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(LSM) | _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         OCR1C = 0xFF;                           // TOP value
24
25         OCR1D = OCR1B = OCR1A = 0;              // initial stride is 0
26
27         DDRB  &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // tristate it
28         PORTB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // set to zero
29 }
30
31 void pwm_on(unsigned char n)
32 {
33         switch (n) {
34         case 0: DDRB |= _BV(PB1); break;
35         case 1: DDRB |= _BV(PB3); break;
36         case 2: DDRB |= _BV(PB5); break;
37         }
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, unsigned char stride)
50 {
51         switch (n) {
52         case 0: OCR1A = stride; break;
53         case 1: OCR1B = stride; break;
54         case 2: OCR1D = stride; break;
55         }
56 }
57
58 #if 0
59 static void inline pwm_handler()
60 {
61         OCR1A = pwmval[0];
62         OCR1B = pwmval[1];
63         OCR1D = pwmval[2];
64         TIMSK &= ~_BV(TOIE1);
65 }
66
67 ISR(TIMER1_OVF_vect)
68 {
69         pwm_handler();
70 }
71 #endif
72