2 #include <avr/interrupt.h>
10 //#define NUM_ADCS ZERO_ADC
13 volatile static unsigned char current_adc;
14 volatile unsigned char adc_enabled;
15 volatile unsigned char need_battery_adc, need_pwmled_adc;
16 static uint16_t adc_sum, read_zero, drop_count, read_count, n_reads_log;
17 volatile uint16_t jiffies;
19 static void setup_mux(unsigned char n)
21 /* ADC numbering: PWM LEDs first, then others, zero at the end */
23 case 0: // pwmled 1: 1.1V, ADC3 (PB3), single-ended
24 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
26 case 1: // battery voltage: 1.1V, ADC1 (PB2), single-ended
27 ADMUX = _BV(REFS1) | _BV(MUX0);
29 case ZERO_ADC: // zero: 1.1V, GND, single-ended
30 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
37 if (need_battery_adc) {
44 } else if (need_pwmled_adc) {
48 read_count = 1 << PWMLED_ADC_SHIFT;
49 n_reads_log = PWMLED_ADC_SHIFT;
65 // set up mux, start one-shot conversion
69 setup_mux(current_adc);
75 void timer_start_slow_adcs()
77 if (current_slow_adc > N_PWMLEDS) { // Don't start if in progress
78 log_byte(0x80 + current_slow_adc);
80 current_slow_adc = NUM_ADCS;
81 // TODO: kick the watchdog here
87 * Single synchronous ADC conversion.
88 * Has to be called with IRQs disabled (or with the ADC IRQ disabled).
90 static uint16_t read_adc_sync()
94 ADCSRA |= _BV(ADSC); // start the conversion
96 // wait for the conversion to finish
97 while((ADCSRA & _BV(ADIF)) == 0)
101 ADCSRA |= _BV(ADIF); // clear the IRQ flag
108 need_battery_adc = 0;
114 ACSR |= _BV(ACD); // but disable the analog comparator
116 ADCSRA = _BV(ADEN) // enable
117 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
118 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
120 // ADCSRB |= _BV(GSEL); // gain 8 or 32
122 // Disable digital input on all bits used by ADC
123 DIDR0 = _BV(ADC3D) | _BV(ADC2D);
126 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
128 /* Do first conversion and drop the result */
131 ADCSRA |= _BV(ADIE); // enable IRQ
144 ISR(ADC_vect) { // IRQ handler
145 uint16_t adcval = ADCW;
148 setup_mux(current_adc);
150 ADCSRA |= _BV(ADSC); // drop this one, start the next
155 ADCSRA |= _BV(ADSC); // drop this one, start the next
161 ADCSRA |= _BV(ADSC); // immediately start the next conversion
168 * Now we have performed read_count measurements and have them
171 switch (current_adc) {
173 // pwmled_adc(current_adc, adc_sum);
177 battery_adc(adc_sum);