2 #include <avr/interrupt.h>
10 //#define NUM_ADCS ZERO_ADC
13 volatile static unsigned char current_adc, current_slow_adc;
14 static uint16_t adc_sum, read_zero, drop_count, read_count, n_reads_log;
16 static void setup_mux(unsigned char n)
18 /* ADC numbering: PWM LEDs first, then others, zero at the end */
20 case 0: // pwmled 1: 1.1V, ADC3 (PB3), single-ended
21 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
23 case ZERO_ADC: // zero: 1.1V, GND, single-ended
24 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
32 if (current_adc == 0) {
33 if (current_slow_adc > N_PWMLEDS) {
34 // read one of the non-PWMLED ADCs
35 current_adc = --current_slow_adc;
37 // no more non-PWMLEDs to do, start with PWMLEDs
38 current_adc = N_PWMLEDS-1;
40 } else if (current_adc >= N_PWMLEDS) {
41 // one of the non-PWMLED ADCs just finished, skip to PWMLEDs.
42 current_adc = N_PWMLEDS-1;
48 // single ADC for testing only
53 log_byte(0x90 + current_adc); // debug ADC switching
60 read_count = 1 << PWMLED_ADC_SHIFT;
61 n_reads_log = PWMLED_ADC_SHIFT;
63 // set up mux, start one-shot conversion
67 setup_mux(current_adc);
73 void timer_start_slow_adcs()
75 if (current_slow_adc > N_PWMLEDS) { // Don't start if in progress
76 log_byte(0x80 + current_slow_adc);
78 current_slow_adc = NUM_ADCS;
79 // TODO: kick the watchdog here
85 * Single synchronous ADC conversion.
86 * Has to be called with IRQs disabled (or with the ADC IRQ disabled).
88 static uint16_t read_adc_sync()
92 ADCSRA |= _BV(ADSC); // start the conversion
94 // wait for the conversion to finish
95 while((ADCSRA & _BV(ADIF)) == 0)
99 ADCSRA |= _BV(ADIF); // clear the IRQ flag
106 current_slow_adc = NUM_ADCS;
110 ACSR |= _BV(ACD); // but disable the analog comparator
112 ADCSRA = _BV(ADEN) // enable
113 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
114 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
116 // ADCSRB |= _BV(GSEL); // gain 8 or 32
118 // Disable digital input on all bits used by ADC
119 DIDR0 = _BV(ADC3D) | _BV(ADC2D);
122 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
124 /* Do first conversion and drop the result */
127 ADCSRA |= _BV(ADIE); // enable IRQ
139 static void adc1_gain20_adc(uint16_t adcsum)
142 adc1_gain20_offset += adcsum
143 - (adc1_gain20_offset >> ADC1_GAIN20_OFFSET_SHIFT);
147 static void inline adc_based_timer()
149 static uint16_t pattern_counter;
151 if (++pattern_counter > 250) {
153 patterns_next_tick();
157 ISR(ADC_vect) { // IRQ handler
158 uint16_t adcval = ADCW;
163 setup_mux(current_adc);
165 ADCSRA |= _BV(ADSC); // drop this one, start the next
170 ADCSRA |= _BV(ADSC); // drop this one, start the next
176 ADCSRA |= _BV(ADSC); // immediately start the next conversion
183 * Now we have performed read_count measurements and have them
186 switch (current_adc) {
188 // pwmled_adc(current_adc, adc_sum);