#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
+#include <util/atomic.h>
#include "lights.h"
static uint16_t pwm[N_PWMLEDS];
static volatile unsigned char step;
+static void enable_pll()
+{
+ /* Async clock */
+ PLLCSR = _BV(PLLE);
+
+ /* Synchronize to the phase lock */
+ _delay_us(100);
+ while ((PLLCSR & _BV(PLOCK)) == 0)
+ ;
+ PLLCSR |= _BV(PCKE);
+}
+
void init_pwm()
{
int i;
for (i = 0; i < N_PWMLEDS; i++)
pwm[i] = 0;
- /* Async clock */
- PLLCSR = _BV(PLLE);
-
- /* Synchronize to the phase lock */
- _delay_ms(1);
- while ((PLLCSR & _BV(PLOCK)) == 0)
- ;
- PLLCSR |= _BV(PCKE);
+ enable_pll();
// PWM channel D is inverted, ...
TCCR1C = _BV(COM1D1) | _BV(COM1D0) | _BV(PWM1D);
TCCR1D = TCCR1C = TCCR1B = TCCR1A = 0;
TIMSK = 0;
TIFR = 0;
+
+ PLLCSR &= ~(_BV(PLLE) | _BV(PCKE));
}
void pwm_off(unsigned char n)
{
- pwm[n] = 0;
-
- switch (n) {
- case 0: DDRB &= ~_BV(PB1); break;
- case 1: DDRB &= ~_BV(PB3); break;
- case 2: DDRB &= ~_BV(PB5); break;
+ ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
+ pwm[n] = 0;
+
+ switch (n) {
+ case 0: DDRB &= ~_BV(PB1); break;
+ case 1: DDRB &= ~_BV(PB3); break;
+ case 2: DDRB &= ~_BV(PB5); break;
+ }
}
}
case 0:
TC1H = hi;
OCR1A = lo;
- DDRB |= _BV(PB1);
break;
case 1:
TC1H = hi;
OCR1B = lo;
- DDRB |= _BV(PB3);
break;
case 2:
TC1H = hi;
OCR1D = lo;
- DDRB |= _BV(PB5);
break;
}
}
if (((stride + (1 << PWM_STEP_SHIFT)) >> PWM_STEP_SHIFT) >= PWM_MAX)
stride = PWM_MAX << PWM_STEP_SHIFT;
- pwm[n] = stride;
- pwm_update_hw(n);
+ ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
+ pwm[n] = stride;
+
+ pwm_update_hw(n);
+
+ switch(n) {
+ case 0: DDRB |= _BV(PB1); break;
+ case 1: DDRB |= _BV(PB3); break;
+ case 2: DDRB |= _BV(PB5); break;
+ }
+ }
}
void pwm_timer()
pwm_update_hw(i);
}
-#if 0
-static void inline pwm_handler()
-{
- OCR1A = pwmval[0];
- OCR1B = pwmval[1];
- OCR1D = pwmval[2];
- TIMSK &= ~_BV(TOIE1);
-}
-
-ISR(TIMER1_OVF_vect)
-{
- pwm_handler();
-}
-#endif
-