]> www.fi.muni.cz Git - bike-lights.git/blob - adc.c
ambient light sensor
[bike-lights.git] / adc.c
1 #include <avr/io.h>
2 #include <avr/interrupt.h>
3
4 #include "lights.h"
5
6 static unsigned char adc_mux[] = { // pwmleds should be first
7         // 0: pwmled 0: 1.1V, ADC3 (PA4), single-ended
8         _BV(REFS1) | _BV(MUX1) | _BV(MUX0),
9         // 1: pwmled 1: 1.1V, ADC0,1 (PA0,1), gain 1 or 8
10         _BV(REFS1) | _BV(MUX3) | _BV(MUX2),
11         // 2: pwmled 2: 1.1V, ADC2,1 (PA2,1), gain 1 or 8
12         _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1) | _BV(MUX0),
13         // 3: ambient light: 1.1V, ADC4 (PA5), single-ended
14         _BV(REFS1) | _BV(MUX2),
15         // 4: batt voltage: 1.1V, ADC5 (PA6), single-ended
16         _BV(REFS1) | _BV(MUX2) | _BV(MUX0),
17 };
18
19 #define AMBIENT_ADC N_PWMLEDS
20
21 #define LAST_ADC (sizeof(adc_mux)/sizeof(char))
22 volatile static unsigned char current_adc = LAST_ADC;
23
24 static void start_next_adc()
25 {
26         while (current_adc > 0) {
27                 --current_adc;
28
29                 // test if current_adc should be measured
30                 if (current_adc < N_PWMLEDS && pwmled_is_on(current_adc))
31                         goto found;
32                 if (current_adc == AMBIENT_ADC)
33                         goto found;
34                 // TODO battery sense, etc.
35         }
36
37         // all ADCs have been handled
38         current_adc = LAST_ADC;
39         return;
40 found:
41         // ADCSRB |= _BV(GSEL); // gain 8 or 32
42         ADMUX = adc_mux[current_adc]; // set up mux, start one-shot conversion
43         ADCSRA |= _BV(ADSC);
44 }
45
46 void init_adc()
47 {
48         ADCSRA = _BV(ADEN)                      // enable
49                 | _BV(ADPS1) | _BV(ADPS0)       // CLK/8 = 125 kHz
50                 // | _BV(ADPS2)                 // CLK/16 = 62.5 kHz
51                 ;
52         ADCSRB |= _BV(GSEL); // gain 8 or 32
53
54         // Disable digital input on all bits used by ADC
55         DIDR0 = _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D) | _BV(ADC3D)
56                 | _BV(ADC4D) | _BV(ADC5D);
57
58         ADCSRA |= _BV(ADSC);
59
60         /* Do first conversion and drop the result */
61         while ((ADCSRA & _BV(ADIF)) == 0)
62                 ;
63         ADCSRA |= _BV(ADIF); // clear the IRQ flag
64
65         ADCSRA |= _BV(ADIE); // enable IRQ
66 }
67
68 ISR(ADC_vect) { // IRQ handler
69         uint16_t adcval = ADCW;
70
71         if (current_adc < N_PWMLEDS)
72                 pwmled_adc(current_adc, adcval);
73         if (current_adc == AMBIENT_ADC)
74                 ambient_adc(adcval);
75         // TODO battery sense, etc.
76         
77         start_next_adc();
78 }
79
80 void timer_start_adcs()
81 {
82         if (current_adc == LAST_ADC) // Don't start if in progress
83                 start_next_adc();
84 }
85