]> www.fi.muni.cz Git - bike-lights.git/blob - lights.c
aa018d977d61d8156b43e3f64e29a837d388b8b7
[bike-lights.git] / lights.c
1 #include <avr/io.h>
2 #include <avr/eeprom.h>
3 #include <util/delay.h>
4 #include <avr/sleep.h>
5 #include <avr/interrupt.h>
6
7 uint16_t pwmee EEMEM;
8 volatile uint16_t adcval;
9
10 volatile struct
11 {
12   uint8_t tmr_int: 1;
13   uint8_t adc_int: 1;
14   uint8_t rx_int: 1;
15 }
16 intflags;
17
18
19 unsigned char debug EEMEM = 1;
20
21 ISR(ADC_vect)
22 {
23         adcval = ADCW;
24         ADCSRA &= ~_BV(ADIE);         /* disable ADC interrupt */
25         intflags.adc_int = 1;
26 }
27
28 ISR(TIMER1_OVF_vect)
29 {
30         TIMSK &= ~_BV(TOIE1);
31         intflags.tmr_int = 1;
32 }
33
34 int main(void)
35 {
36         char seen = 0;
37
38         TCCR1C = _BV(COM1D0) | _BV(COM1D1) | _BV(PWM1D);
39         TCCR1A = _BV(COM1A0) | _BV(COM1A1) | _BV(COM1B0) | _BV(COM1B1) | _BV(PWM1A) | _BV(PWM1B);
40         TCCR1B = 0x80| _BV(CS13) | _BV(CS10);
41         TC1H  = 0x03;
42         OCR1C = 0xFF;
43         OCR1D = OCR1B = OCR1A = 0x40;
44         TCNT1 = 0;
45         DDRB |= _BV( PB5 ) | _BV( PB1 ) | _BV( PB3 );
46         PORTB &= ~(_BV( PB5 ) | _BV( PB1 ) | _BV( PB3 ));
47         TIMSK = _BV(TOIE1);
48
49         ADCSRA = _BV(ADEN) | _BV(ADATE) | _BV(ADPS1) | _BV(ADPS0);
50         ADMUX = _BV(REFS1) | _BV(MUX0);
51         // ADCSRB = _BV(REFS2); 
52         DIDR0 = _BV(ADC1D) | _BV(AREFD);
53
54         sei();
55         while (1) {
56                 unsigned char pwmhi, pwmlo;
57
58                 if (intflags.adc_int) {
59                         intflags.adc_int = 0;
60
61                         if (adcval > 0x3C0)
62                                 adcval = 0x3C0;
63                         if (adcval < 1)
64                                 adcval = 1;
65                         pwmhi = adcval >> 8;
66                         pwmlo = adcval & 0xFF;
67
68                         TC1H = pwmhi;
69                         OCR1D = pwmlo;
70
71                         TC1H = pwmhi;
72                         OCR1B = pwmlo;
73
74                         TC1H = pwmhi;
75                         OCR1A = pwmlo;
76
77                         TIMSK |= _BV(TOIE1);
78                 }
79
80                 if (intflags.tmr_int) {
81                         intflags.tmr_int = 0;
82                         ADCSRA |= _BV(ADIE) | _BV(ADSC);
83                 }
84
85                 sleep_mode();
86
87 #if 0
88                 if (!seen) {
89                         seen = 1;
90                         eeprom_write_byte(&debug, 2);
91                 }
92 #endif
93         }
94
95     DDRA |= _BV( PA0 );
96     while( 1 ) { 
97         PORTA |=  _BV( PA0 );
98         _delay_ms(2000);
99         PORTA &=~ _BV( PA0 );
100         _delay_ms(2000);
101     }
102 }