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;
15 volatile uint16_t jiffies;
17 static void setup_mux(unsigned char n)
19 /* ADC numbering: PWM LEDs first, then others, zero at the end */
21 case 0: // pwmled 1: 1.1V, ADC3 (PB3), single-ended
22 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
24 case ZERO_ADC: // zero: 1.1V, GND, single-ended
25 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
33 if (current_adc == 0) {
34 if (current_slow_adc > N_PWMLEDS) {
35 // read one of the non-PWMLED ADCs
36 current_adc = --current_slow_adc;
38 // no more non-PWMLEDs to do, start with PWMLEDs
39 current_adc = N_PWMLEDS-1;
41 } else if (current_adc >= N_PWMLEDS) {
42 // one of the non-PWMLED ADCs just finished, skip to PWMLEDs.
43 current_adc = N_PWMLEDS-1;
49 // single ADC for testing only
54 log_byte(0x90 + current_adc); // debug ADC switching
61 read_count = 1 << PWMLED_ADC_SHIFT;
62 n_reads_log = PWMLED_ADC_SHIFT;
64 // set up mux, start one-shot conversion
68 setup_mux(current_adc);
74 void timer_start_slow_adcs()
76 if (current_slow_adc > N_PWMLEDS) { // Don't start if in progress
77 log_byte(0x80 + current_slow_adc);
79 current_slow_adc = NUM_ADCS;
80 // TODO: kick the watchdog here
86 * Single synchronous ADC conversion.
87 * Has to be called with IRQs disabled (or with the ADC IRQ disabled).
89 static uint16_t read_adc_sync()
93 ADCSRA |= _BV(ADSC); // start the conversion
95 // wait for the conversion to finish
96 while((ADCSRA & _BV(ADIF)) == 0)
100 ADCSRA |= _BV(ADIF); // clear the IRQ flag
107 current_slow_adc = NUM_ADCS;
111 ACSR |= _BV(ACD); // but disable the analog comparator
113 ADCSRA = _BV(ADEN) // enable
114 | _BV(ADPS1) | _BV(ADPS0) // CLK/8 = 125 kHz
115 // | _BV(ADPS2) // CLK/16 = 62.5 kHz
117 // ADCSRB |= _BV(GSEL); // gain 8 or 32
119 // Disable digital input on all bits used by ADC
120 DIDR0 = _BV(ADC3D) | _BV(ADC2D);
123 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
125 /* Do first conversion and drop the result */
128 ADCSRA |= _BV(ADIE); // enable IRQ
140 static void adc1_gain20_adc(uint16_t adcsum)
143 adc1_gain20_offset += adcsum
144 - (adc1_gain20_offset >> ADC1_GAIN20_OFFSET_SHIFT);
148 static void inline adc_based_timer()
150 static unsigned char count;
152 if (++count < 40) // about 100 Hz jiffies
158 if ((jiffies & 0x0007) == 0) {
159 patterns_next_tick();
161 timer_check_buttons();
164 ISR(ADC_vect) { // IRQ handler
165 uint16_t adcval = ADCW;
170 setup_mux(current_adc);
172 ADCSRA |= _BV(ADSC); // drop this one, start the next
177 ADCSRA |= _BV(ADSC); // drop this one, start the next
183 ADCSRA |= _BV(ADSC); // immediately start the next conversion
190 * Now we have performed read_count measurements and have them
193 switch (current_adc) {
195 // pwmled_adc(current_adc, adc_sum);