From: Jan "Yenya" Kasprzak Date: Fri, 4 Jan 2013 14:50:14 +0000 (+0100) Subject: adc.c: routine for synchronous conversion X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?a=commitdiff_plain;h=f31e81252594197944d593cb73c5a44856ee4893;p=bike-lights.git adc.c: routine for synchronous conversion --- diff --git a/firmware/adc.c b/firmware/adc.c index f5d846f..abbd3ba 100644 --- a/firmware/adc.c +++ b/firmware/adc.c @@ -62,6 +62,26 @@ static void start_next_adc() ADCSRA |= _BV(ADSC); } +/* + * Single synchronous ADC conversion. + * Has to be called with IRQs disabled (or with the ADC IRQ disabled). + */ +static uint16_t read_adc_sync() +{ + uint16_t rv; + + ADCSRA |= _BV(ADSC); // start the conversion + + // wait for the conversion to finish + while((ADCSRA & _BV(ADIF)) == 0) + ; + + rv = ADCW; + ADCSRA |= _BV(ADIF); // clear the IRQ flag + + return rv; +} + void init_adc() { unsigned char i; @@ -79,24 +99,15 @@ void init_adc() // 1.1V, ADC1,1, gain 20 ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0); - ADCSRA |= _BV(ADSC); /* Do first conversion and drop the result */ - while ((ADCSRA & _BV(ADIF)) == 0) - ; - ADCSRA |= _BV(ADIF); // clear the IRQ flag + read_adc_sync(); adc1_gain20_offset = 0; for (i = 0; i < (1 << ADC1_GAIN20_OFFSET_SHIFT); i++) { - ADCSRA |= _BV(ADSC); - - while ((ADCSRA & _BV(ADIF)) == 0) - ; - adc1_gain20_offset += ADCW + adc1_gain20_offset += read_adc_sync() - (adc1_gain20_offset >> ADC1_GAIN20_OFFSET_SHIFT); - - ADCSRA |= _BV(ADIF); // clear the IRQ flag } ADCSRA |= _BV(ADIE); // enable IRQ