2 #include <avr/interrupt.h>
9 //#define NUM_ADCS ZERO_ADC
12 volatile static unsigned char current_adc, current_slow_adc;
13 static uint16_t adc_sum, read_zero, drop_count, read_count, n_reads_log;
15 static void setup_mux(unsigned char n)
17 /* ADC numbering: PWM LEDs first, then others, zero at the end */
19 case 0: // pwmled 1: 1.1V, ADC3 (PB3), single-ended
20 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
22 case ZERO_ADC: // zero: 1.1V, GND, single-ended
23 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
31 if (current_adc == 0) {
32 if (current_slow_adc > N_PWMLEDS) {
33 // read one of the non-PWMLED ADCs
34 current_adc = --current_slow_adc;
36 // no more non-PWMLEDs to do, start with PWMLEDs
37 current_adc = N_PWMLEDS-1;
39 } else if (current_adc >= N_PWMLEDS) {
40 // one of the non-PWMLED ADCs just finished, skip to PWMLEDs.
41 current_adc = N_PWMLEDS-1;
47 // single ADC for testing only
52 log_byte(0x90 + current_adc); // debug ADC switching
59 read_count = 1 << PWMLED_ADC_SHIFT;
60 n_reads_log = PWMLED_ADC_SHIFT;
62 // set up mux, start one-shot conversion
66 setup_mux(current_adc);
72 void timer_start_slow_adcs()
74 if (current_slow_adc > N_PWMLEDS) { // Don't start if in progress
75 log_byte(0x80 + current_slow_adc);
77 current_slow_adc = NUM_ADCS;
78 // TODO: kick the watchdog here
84 * Single synchronous ADC conversion.
85 * Has to be called with IRQs disabled (or with the ADC IRQ disabled).
87 static uint16_t read_adc_sync()
91 ADCSRA |= _BV(ADSC); // start the conversion
93 // wait for the conversion to finish
94 while((ADCSRA & _BV(ADIF)) == 0)
98 ADCSRA |= _BV(ADIF); // clear the IRQ flag
105 current_slow_adc = NUM_ADCS;
108 ADCSRA = _BV(ADEN) // enable
109 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
110 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
112 // ADCSRB |= _BV(GSEL); // gain 8 or 32
114 // Disable digital input on all bits used by ADC
115 DIDR0 = _BV(ADC3D) | _BV(ADC2D);
118 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
120 /* Do first conversion and drop the result */
123 ADCSRA |= _BV(ADIE); // enable IRQ
135 static void adc1_gain20_adc(uint16_t adcsum)
138 adc1_gain20_offset += adcsum
139 - (adc1_gain20_offset >> ADC1_GAIN20_OFFSET_SHIFT);
143 static void inline adc_based_timer()
145 static uint16_t pattern_counter;
147 if (++pattern_counter > 250) {
149 patterns_next_tick();
153 ISR(ADC_vect) { // IRQ handler
154 uint16_t adcval = ADCW;
159 setup_mux(current_adc);
161 ADCSRA |= _BV(ADSC); // drop this one, start the next
166 ADCSRA |= _BV(ADSC); // drop this one, start the next
172 ADCSRA |= _BV(ADSC); // immediately start the next conversion
179 * Now we have performed read_count measurements and have them
182 switch (current_adc) {
184 // pwmled_adc(current_adc, adc_sum);