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 0: 1.1V, ADC3 (PA4), single-ended
9 _BV(REFS1) | _BV(MUX1) | _BV(MUX0),
10 // 1: pwmled 1: 1.1V, ADC0,1 (PA0,1), gain 1 or 8
11 _BV(REFS1) | _BV(MUX3) | _BV(MUX2),
12 // 2: pwmled 2: 1.1V, ADC2,1 (PA2,1), gain 1 or 8
13 _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1) | _BV(MUX0),
14 // 3: ambient light: 1.1V, ADC4 (PA5), single-ended
15 _BV(REFS1) | _BV(MUX2),
16 // 4: batt voltage: 1.1V, ADC5 (PA6), single-ended
17 _BV(REFS1) | _BV(MUX2) | _BV(MUX0),
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;
44 // ADCSRB |= _BV(GSEL); // gain 8 or 32
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) | _BV(ADC3D)
63 | _BV(ADC4D) | _BV(ADC5D);
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
75 ISR(ADC_vect) { // IRQ handler
76 uint16_t adcval = ADCW;
80 log_byte(current_adc);
90 if (current_adc < N_PWMLEDS)
91 pwmled_adc(current_adc, adcval);
92 if (current_adc == AMBIENT_ADC)
94 // TODO battery sense, etc.
99 void timer_start_adcs()
101 if (current_adc == LAST_ADC) // Don't start if in progress