]> www.fi.muni.cz Git - tinyboard.git/blob - projects/step-up/pwm.c
power off by default, power on/off with button
[tinyboard.git] / projects / step-up / pwm.c
1 #include <avr/io.h>
2 #include <avr/interrupt.h>
3 #include <avr/power.h>
4 #include <util/delay.h>
5 #include <util/atomic.h>
6
7 #include "lights.h"
8
9 /*
10  * Single PWM channel on OC1B (pin PB4 of Tiny45).
11  * Counts from 0 to 0xFF, without OCR1C compare.
12  */
13
14 static void inline enable_pll()
15 {
16         /* Async clock */
17         PLLCSR = _BV(PLLE);
18
19         /* Synchronize to the phase lock */
20         _delay_us(100);
21         while ((PLLCSR & _BV(PLOCK)) == 0)
22                 ;
23         PLLCSR |= _BV(PCKE);
24 }
25
26 void init_pwm()
27 {
28         power_timer1_enable();
29
30         enable_pll();
31
32         TCCR1 = _BV(CTC1) | _BV(CS10);  // no clock prescaling
33         GTCCR = _BV(COM1B1) | _BV(PWM1B);
34
35         OCR1C = PWM_MAX;
36         OCR1B = 0;              // initial stride is 0
37
38         DDRB  &= ~_BV(PB4); // tristate it
39         PORTB &= ~_BV(PB4); // set to zero
40 }
41
42 void susp_pwm()
43 {
44         DDRB &= ~(_BV( PB4 ));
45         PORTB &= ~(_BV( PB4 ));
46         TCCR1 = 0;
47         TIMSK = 0;
48         TIFR = 0;
49
50         PLLCSR &= ~(_BV(PLLE) | _BV(PCKE));
51 }
52
53 void pwm_off()
54 {
55         OCR1B = 0;
56         DDRB &= ~_BV(PB4);
57 }
58
59 void pwm_set(uint8_t stride)
60 {
61         OCR1B = stride;
62         DDRB |= _BV(PB4);
63 }