2 #include <avr/interrupt.h>
10 //#define NUM_ADCS ZERO_ADC
13 volatile static unsigned char current_adc;;
14 volatile unsigned char need_battery_adc;
15 static uint16_t adc_sum, read_zero, drop_count, read_count, n_reads_log;
16 volatile uint16_t jiffies;
18 static void setup_mux(unsigned char n)
20 /* ADC numbering: PWM LEDs first, then others, zero at the end */
22 case 0: // pwmled 1: 1.1V, ADC3 (PB3), single-ended
23 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
25 case 1: // battery voltage: 1.1V, ADC1 (PB2), single-ended
26 ADMUX = _BV(REFS1) | _BV(MUX0);
28 case ZERO_ADC: // zero: 1.1V, GND, single-ended
29 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
36 if (need_battery_adc) {
47 read_count = 1 << PWMLED_ADC_SHIFT;
48 n_reads_log = PWMLED_ADC_SHIFT;
54 // set up mux, start one-shot conversion
58 setup_mux(current_adc);
64 void timer_start_slow_adcs()
66 if (current_slow_adc > N_PWMLEDS) { // Don't start if in progress
67 log_byte(0x80 + current_slow_adc);
69 current_slow_adc = NUM_ADCS;
70 // TODO: kick the watchdog here
76 * Single synchronous ADC conversion.
77 * Has to be called with IRQs disabled (or with the ADC IRQ disabled).
79 static uint16_t read_adc_sync()
83 ADCSRA |= _BV(ADSC); // start the conversion
85 // wait for the conversion to finish
86 while((ADCSRA & _BV(ADIF)) == 0)
90 ADCSRA |= _BV(ADIF); // clear the IRQ flag
101 ACSR |= _BV(ACD); // but disable the analog comparator
103 ADCSRA = _BV(ADEN) // enable
104 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
105 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
107 // ADCSRB |= _BV(GSEL); // gain 8 or 32
109 // Disable digital input on all bits used by ADC
110 DIDR0 = _BV(ADC3D) | _BV(ADC2D);
113 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
115 /* Do first conversion and drop the result */
118 ADCSRA |= _BV(ADIE); // enable IRQ
129 ISR(ADC_vect) { // IRQ handler
130 uint16_t adcval = ADCW;
133 setup_mux(current_adc);
135 ADCSRA |= _BV(ADSC); // drop this one, start the next
140 ADCSRA |= _BV(ADSC); // drop this one, start the next
146 ADCSRA |= _BV(ADSC); // immediately start the next conversion
153 * Now we have performed read_count measurements and have them
156 switch (current_adc) {
158 // pwmled_adc(current_adc, adc_sum);
162 battery_adc(adc_sum);