]> www.fi.muni.cz Git - bike-lights.git/blob - adc.c
gpio.c: gpio leds and other tools
[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 LAST_ADC (sizeof(adc_mux)/sizeof(char))
20 volatile static unsigned char current_adc = LAST_ADC;
21
22 static void start_next_adc()
23 {
24         while (current_adc > 0) {
25                 --current_adc;
26
27                 // test if current_adc should be measured
28                 if (current_adc < N_PWMLEDS && pwmled_is_on(current_adc))
29                         goto found;
30                 // TODO ambient light, battery sense, etc.
31         }
32
33         // all ADCs have been handled
34         current_adc = LAST_ADC;
35         return;
36 found:
37         // ADCSRB |= _BV(GSEL); // gain 8 or 32
38         ADMUX = adc_mux[current_adc]; // set up mux, start one-shot conversion
39         ADCSRA |= _BV(ADSC);
40 }
41
42 void init_adc()
43 {
44         ADCSRA = _BV(ADEN)                      // enable
45                 | _BV(ADPS1) | _BV(ADPS0)       // CLK/8 = 125 kHz
46                 // | _BV(ADPS2)                 // CLK/16 = 62.5 kHz
47                 ;
48         ADCSRB |= _BV(GSEL); // gain 8 or 32
49
50         // Disable digital input on all bits used by ADC
51         DIDR0 = _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D) | _BV(ADC3D)
52                 | _BV(ADC4D) | _BV(ADC5D);
53
54         ADCSRA |= _BV(ADSC);
55
56         /* Do first conversion and drop the result */
57         while ((ADCSRA & _BV(ADIF)) == 0)
58                 ;
59         ADCSRA |= _BV(ADIF); // clear the IRQ flag
60
61         ADCSRA |= _BV(ADIE); // enable IRQ
62 }
63
64 ISR(ADC_vect) { // IRQ handler
65         uint16_t adcval = ADCW;
66
67         if (current_adc < N_PWMLEDS)
68                 pwmled_adc(current_adc, adcval);
69         // TODO ambient light, battery sense, etc.
70         
71         start_next_adc();
72 }
73
74 void timer_start_adcs()
75 {
76         if (current_adc == LAST_ADC) // Don't start if in progress
77                 start_next_adc();
78 }
79