2 #include <avr/interrupt.h>
4 #include <util/delay.h>
5 #include <util/atomic.h>
9 #define PWM_STEP_SHIFT 2 /* sub-LSB precision */
10 #define PWM_TOP (((PWM_MAX) + (4 << (PWM_STEP_SHIFT))) >> (PWM_STEP_SHIFT))
12 #error PWM_TOP too high
15 static uint16_t pwm[N_PWMLEDS];
16 static volatile unsigned char step;
17 static unsigned char channels_running, pll_enabled;
19 static void enable_pll()
24 /* Synchronize to the phase lock */
26 while ((PLLCSR & _BV(PLOCK)) == 0)
41 for (i = 0; i < N_PWMLEDS; i++)
44 // PWM channel D is inverted, ...
45 TCCR1C = _BV(COM1D1) | _BV(COM1D0) | _BV(PWM1D);
46 // PWM channels A and B are not
47 TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(PWM1A) | _BV(PWM1B);
49 TCCR1B = _BV(CS10); // no clock prescaling
52 OCR1C = PWM_TOP & 0xFF; // TOP value
54 TC1H = PWM_TOP >> 8; // PWM3 is inverted
55 OCR1D = PWM_TOP & 0xFF;
58 OCR1B = OCR1A = 0; // initial stride is 0
60 DDRB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // tristate it
61 PORTB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // set to zero
68 for (i = 0; i < N_PWMLEDS; i++)
71 DDRB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 ));
72 TCCR1D = TCCR1C = TCCR1B = TCCR1A = 0;
76 PLLCSR &= ~(_BV(PLLE) | _BV(PCKE));
79 void pwm_off(unsigned char n)
81 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
83 channels_running &= ~(1 << n);
86 case 0: DDRB &= ~_BV(PB1); break;
87 case 1: DDRB &= ~_BV(PB3); break;
88 case 2: DDRB &= ~_BV(PB5); break;
93 static void pwm_update_hw(unsigned char n)
96 uint16_t stride = (pwm[n] + step) >> PWM_STEP_SHIFT;
99 stride = PWM_TOP - stride;
120 void pwm_set(unsigned char n, uint16_t stride)
122 if (stride > PWM_MAX)
125 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
127 channels_running |= (1 << n);
130 power_timer1_enable();
137 case 0: DDRB |= _BV(PB1); break;
138 case 1: DDRB |= _BV(PB3); break;
139 case 2: DDRB |= _BV(PB5); break;
148 if (++step >= (1 << PWM_STEP_SHIFT))
151 for (i = 0; i < N_PWMLEDS; i++)
156 void pwm_disable_if_not_needed()
158 if (channels_running)
162 DDRB &= ~(_BV(PB1) | _BV(PB3) | _BV(PB5));
163 PLLCSR &= ~(_BV(PLLE) | _BV(PCKE));
165 power_timer1_disable();