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 TCCR1 = _BV(CTC1) | _BV(CS10); // no clock prescaling
41 GTCCR = _BV(COM1A1) | _BV(COM1B1) | _BV(PWM1A) | _BV(PWM1B);
44 OCR1A = OCR1B = 0; // initial stride is 0
46 DDRB &= ~(_BV( PB1 ) | _BV( PB4 )); // tristate it
47 PORTB &= ~(_BV( PB1 ) | _BV( PB4 )); // set to zero
55 for (i = 0; i < N_PWMLEDS; i++)
58 DDRB &= ~(_BV( PB1 ) | _BV( PB3 ) | _BV( PB5 ));
59 TCCR1D = TCCR1C = TCCR1B = TCCR1A = 0;
63 PLLCSR &= ~(_BV(PLLE) | _BV(PCKE));
67 void pwm_off(unsigned char n)
69 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
73 case 0: DDRB &= ~_BV(PB1); break;
74 case 1: DDRB &= ~_BV(PB4); break;
79 static void pwm_update_hw(unsigned char n)
81 uint16_t stride = (pwm[n] + step) >> PWM_STEP_SHIFT;
93 void pwm_set(unsigned char n, uint16_t stride)
98 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
104 case 0: DDRB |= _BV(PB1); break;
105 case 1: DDRB |= _BV(PB4); break;
114 if (++step >= (1 << PWM_STEP_SHIFT))
117 for (i = 0; i < N_PWMLEDS; i++)