]> www.fi.muni.cz Git - bike-lights.git/blobdiff - firmware/adc.c
pattern: laser diodes as gpio 4
[bike-lights.git] / firmware / adc.c
index abbd3bac5b93c90c2ad9304b0430165e32aa3805..9155f325ccfd2c857a93c503b2c2f6337a78ad04 100644 (file)
@@ -1,5 +1,6 @@
 #include <avr/io.h>
 #include <avr/interrupt.h>
+#include <util/atomic.h>
 
 #include "lights.h"
 
@@ -14,6 +15,7 @@ static unsigned char sum_shift;
 static unsigned char adc_vals;
 #define ADC1_GAIN20_OFFSET_SHIFT       6
 static uint16_t adc1_gain20_offset;
+static unsigned char handler_running;
 
 static void inline setup_mux(unsigned char n)
 {
@@ -33,7 +35,7 @@ static void inline setup_mux(unsigned char n)
                break;
        case 3: // ambient light: 1.1V, ADC5 (PA6), single-ended
                ADMUX = _BV(REFS1) | _BV(MUX2) | _BV(MUX0);
-               sum_shift = 0; // 1 measurement
+               sum_shift = 3; // 3 measurements
                break;
        case 4: // batt voltage: 1.1V, ADC6 (PA7), single-ended
                ADMUX = _BV(REFS1) | _BV(MUX2) | _BV(MUX1);
@@ -86,6 +88,7 @@ void init_adc()
 {
        unsigned char i;
        current_adc = NUM_ADCS;
+       handler_running = 0;
 
        ADCSRA = _BV(ADEN)                      // enable
                | _BV(ADPS1) | _BV(ADPS0)       // CLK/8 = 125 kHz
@@ -154,13 +157,28 @@ ISR(ADC_vect) { // IRQ handler
                        adc_sum = 0;
        }
 
-       if (current_adc < N_PWMLEDS)
-               pwmled_adc(current_adc, adc_sum);
-       if (current_adc == AMBIENT_ADC)
-               ambient_adc(adcval);
-       if (current_adc == BATTERY_ADC)
-               battery_adc(adcval);
-       
-       start_next_adc();
+       if (handler_running & (1 << current_adc)) {
+               log_byte(0xB0 + current_adc);
+
+               // drop the result, what else to do?
+
+               start_next_adc();
+       } else {
+               unsigned char current_adc_copy = current_adc;
+               uint16_t adc_sum_copy = adc_sum;
+
+               start_next_adc();
+
+               handler_running |= (1 << current_adc_copy);
+               NONATOMIC_BLOCK(NONATOMIC_FORCEOFF) {
+                       if (current_adc_copy < N_PWMLEDS)
+                               pwmled_adc(current_adc_copy, adc_sum_copy);
+                       if (current_adc_copy == AMBIENT_ADC)
+                               ambient_adc(adc_sum_copy);
+                       if (current_adc_copy == BATTERY_ADC)
+                               battery_adc(adc_sum_copy);
+               }
+               handler_running &= ~(1 << current_adc_copy);
+       }
 }