2 #include <avr/interrupt.h>
6 /* ADC numbering: PWM LEDs first, then ambient light sensor, battery sensor */
7 static unsigned char adc_mux[] = { // pwmleds should be first
8 // 0: pwmled 1: 1.1V, ADC0,1 (PA0,1), gain 20
9 _BV(REFS1) | _BV(MUX3) | _BV(MUX1) | _BV(MUX0),
10 // 1: pwmled 2: 1.1V, ADC2,1 (PA2,1), gain 20
11 _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1),
12 // 2: pwmled 3: 1.1V, ADC4 (PA5), single-ended
13 // _BV(REFS1) | _BV(MUX2),
14 // 2: for testing the same as 1
15 _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1),
16 // 3: ambient light: 1.1V, ADC5 (PA6), single-ended
17 _BV(REFS1) | _BV(MUX2) | _BV(MUX0),
18 // 4: batt voltage: 1.1V, ADC6 (PA7), single-ended
19 _BV(REFS1) | _BV(MUX2) | _BV(MUX1),
22 #define AMBIENT_ADC N_PWMLEDS
23 #define BATTERY_ADC (N_PWMLEDS + 1)
25 #define LAST_ADC (sizeof(adc_mux)/sizeof(adc_mux[0]))
26 volatile static unsigned char current_adc;
27 static unsigned char adc_ignore;
29 static void start_next_adc()
31 while (current_adc > 0) {
34 // test if current_adc should be measured
35 if (current_adc < N_PWMLEDS && pwmled_needs_adc(current_adc))
37 if (current_adc == AMBIENT_ADC)
39 // TODO battery sense, etc.
42 // all ADCs have been handled
43 current_adc = LAST_ADC;
44 // TODO: kick the watchdog here.
47 ADMUX = adc_mux[current_adc]; // set up mux, start one-shot conversion
48 adc_ignore = 1; // ignore first reading after mux change
54 current_adc = LAST_ADC;
57 ADCSRA = _BV(ADEN) // enable
58 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
59 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
61 // ADCSRB |= _BV(GSEL); // gain 8 or 32
63 // Disable digital input on all bits used by ADC
64 DIDR0 = _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D)
65 | _BV(ADC4D) | _BV(ADC5D) | _BV(ADC6D);
69 /* Do first conversion and drop the result */
70 while ((ADCSRA & _BV(ADIF)) == 0)
72 ADCSRA |= _BV(ADIF); // clear the IRQ flag
74 ADCSRA |= _BV(ADIE); // enable IRQ
83 ISR(ADC_vect) { // IRQ handler
84 uint16_t adcval = ADCW;
88 log_byte(current_adc);
98 if (current_adc < N_PWMLEDS)
99 pwmled_adc(current_adc, adcval);
100 if (current_adc == AMBIENT_ADC)
102 // TODO battery sense, etc.
107 void timer_start_adcs()
109 if (current_adc == LAST_ADC) // Don't start if in progress