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 // 3: ambient light: 1.1V, ADC5 (PA6), single-ended
15 _BV(REFS1) | _BV(MUX2) | _BV(MUX0),
16 // 4: batt voltage: 1.1V, ADC6 (PA7), single-ended
17 _BV(REFS1) | _BV(MUX2) | _BV(MUX1),
20 #define AMBIENT_ADC N_PWMLEDS
21 #define BATTERY_ADC (N_PWMLEDS + 1)
23 #define LAST_ADC (sizeof(adc_mux)/sizeof(adc_mux[0]))
24 volatile static unsigned char current_adc;
25 static unsigned char adc_ignore;
27 static void start_next_adc()
29 while (current_adc > 0) {
32 // test if current_adc should be measured
33 if (current_adc < N_PWMLEDS && pwmled_needs_adc(current_adc))
35 if (current_adc == AMBIENT_ADC)
37 // TODO battery sense, etc.
40 // all ADCs have been handled
41 current_adc = LAST_ADC;
42 // TODO: kick the watchdog here.
45 ADMUX = adc_mux[current_adc]; // set up mux, start one-shot conversion
46 adc_ignore = 1; // ignore first reading after mux change
52 current_adc = LAST_ADC;
55 ADCSRA = _BV(ADEN) // enable
56 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
57 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
59 // ADCSRB |= _BV(GSEL); // gain 8 or 32
61 // Disable digital input on all bits used by ADC
62 DIDR0 = _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D)
63 | _BV(ADC4D) | _BV(ADC5D) | _BV(ADC6D);
67 /* Do first conversion and drop the result */
68 while ((ADCSRA & _BV(ADIF)) == 0)
70 ADCSRA |= _BV(ADIF); // clear the IRQ flag
72 ADCSRA |= _BV(ADIE); // enable IRQ
81 ISR(ADC_vect) { // IRQ handler
82 uint16_t adcval = ADCW;
86 log_byte(current_adc);
96 if (current_adc < N_PWMLEDS)
97 pwmled_adc(current_adc, adcval);
98 if (current_adc == AMBIENT_ADC)
100 if (current_adc == BATTERY_ADC)
106 void timer_start_adcs()
108 if (current_adc == LAST_ADC) // Don't start if in progress