]> www.fi.muni.cz Git - bike-lights.git/blobdiff - adc.c
lights.c split into more modules
[bike-lights.git] / adc.c
diff --git a/adc.c b/adc.c
new file mode 100644 (file)
index 0000000..a37e958
--- /dev/null
+++ b/adc.c
@@ -0,0 +1,79 @@
+#include <avr/io.h>
+#include <avr/interrupt.h>
+
+#include "lights.h"
+
+static unsigned char adc_mux[] = { // pwmleds should be first
+       // 0: pwmled 0: 1.1V, ADC3 (PA4), single-ended
+       _BV(REFS1) | _BV(MUX1) | _BV(MUX0),
+       // 1: pwmled 1: 1.1V, ADC0,1 (PA0,1), gain 1 or 8
+       _BV(REFS1) | _BV(MUX3) | _BV(MUX2),
+       // 2: pwmled 2: 1.1V, ADC2,1 (PA2,1), gain 1 or 8
+       _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1) | _BV(MUX0),
+       // 3: ambient light: 1.1V, ADC4 (PA5), single-ended
+       _BV(REFS1) | _BV(MUX2),
+       // 4: batt voltage: 1.1V, ADC5 (PA6), single-ended
+       _BV(REFS1) | _BV(MUX2) | _BV(MUX0),
+};
+
+#define LAST_ADC (sizeof(adc_mux)/sizeof(char))
+volatile static unsigned char current_adc = LAST_ADC;
+
+static void start_next_adc()
+{
+       while (current_adc > 0) {
+               --current_adc;
+
+               // test if current_adc should be measured
+               if (current_adc < N_PWMLEDS && pwmled_is_on(current_adc))
+                       goto found;
+               // TODO ambient light, battery sense, etc.
+       }
+
+       // all ADCs have been handled
+       current_adc = LAST_ADC;
+       return;
+found:
+       // ADCSRB |= _BV(GSEL); // gain 8 or 32
+       ADMUX = adc_mux[current_adc]; // set up mux, start one-shot conversion
+       ADCSRA |= _BV(ADSC);
+}
+
+void init_adc()
+{
+       ADCSRA = _BV(ADEN)                      // enable
+               | _BV(ADPS1) | _BV(ADPS0)       // CLK/8 = 125 kHz
+               // | _BV(ADPS2)                 // CLK/16 = 62.5 kHz
+               ;
+       ADCSRB |= _BV(GSEL); // gain 8 or 32
+
+       // Disable digital input on all bits used by ADC
+       DIDR0 = _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D) | _BV(ADC3D)
+               | _BV(ADC4D) | _BV(ADC5D);
+
+       ADCSRA |= _BV(ADSC);
+
+       /* Do first conversion and drop the result */
+       while ((ADCSRA & _BV(ADIF)) == 0)
+               ;
+       ADCSRA |= _BV(ADIF); // clear the IRQ flag
+
+       ADCSRA |= _BV(ADIE); // enable IRQ
+}
+
+ISR(ADC_vect) { // IRQ handler
+       uint16_t adcval = ADCW;
+
+       if (current_adc < N_PWMLEDS)
+               pwmled_adc(current_adc, adcval);
+       // TODO ambient light, battery sense, etc.
+       
+       start_next_adc();
+}
+
+void timer_start_adcs()
+{
+       if (current_adc == LAST_ADC) // Don't start if in progress
+               start_next_adc();
+}
+