2 #include <avr/interrupt.h>
3 #include <util/delay.h>
4 #include <util/atomic.h>
8 #define PWM_STEP_SHIFT 2 /* sub-LSB precision */
9 #define PWM_TOP (((PWM_MAX) + (4 << (PWM_STEP_SHIFT))) >> (PWM_STEP_SHIFT))
11 #error PWM_TOP too high
14 static uint16_t pwm[N_PWMLEDS];
15 static volatile unsigned char step;
17 static void enable_pll()
22 /* Synchronize to the phase lock */
24 while ((PLLCSR & _BV(PLOCK)) == 0)
35 for (i = 0; i < N_PWMLEDS; i++)
40 // PWM channel D is inverted, ...
41 TCCR1C = _BV(COM1D1) | _BV(COM1D0) | _BV(PWM1D);
42 // PWM channels A and B are not
43 TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(PWM1A) | _BV(PWM1B);
45 TCCR1B = _BV(CS10); // no clock prescaling
48 OCR1C = PWM_TOP & 0xFF; // TOP value
50 TC1H = PWM_TOP >> 8; // PWM3 is inverted
51 OCR1D = PWM_TOP & 0xFF;
54 OCR1B = OCR1A = 0; // initial stride is 0
56 DDRB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // tristate it
57 PORTB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 )); // set to zero
64 for (i = 0; i < N_PWMLEDS; i++)
67 DDRB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 ));
68 TCCR1D = TCCR1C = TCCR1B = TCCR1A = 0;
72 PLLCSR &= ~(_BV(PLLE) | _BV(PCKE));
75 void pwm_off(unsigned char n)
77 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
81 case 0: DDRB &= ~_BV(PB1); break;
82 case 1: DDRB &= ~_BV(PB3); break;
83 case 2: DDRB &= ~_BV(PB5); break;
88 static void pwm_update_hw(unsigned char n)
91 uint16_t stride = (pwm[n] + step) >> PWM_STEP_SHIFT;
94 stride = PWM_TOP - stride;
115 void pwm_set(unsigned char n, uint16_t stride)
117 if (stride > PWM_MAX)
120 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
126 case 0: DDRB |= _BV(PB1); break;
127 case 1: DDRB |= _BV(PB3); break;
128 case 2: DDRB |= _BV(PB5); break;
137 if (++step >= (1 << PWM_STEP_SHIFT))
140 for (i = 0; i < N_PWMLEDS; i++)