Chapter 9 – Digital Meets Analog – ADC and DAC
while(!(ADCSRA & 0x10));
result (8 samples) for later averaging
ADCr += ADC_temp;
ADCr = ADCr >> 3; // average the 8 samples
Reading the ADC
We save power by turning off the voltage on the light and temperature sensors
when they are not used, so now we turn them on, in case they are being used.
sbi(PORTF, PF3);
sbi(DDRF, DDF3);
Next we enable the ADC.
sbi(ADCSRA, ADEN); // Enable the ADC
Then we do another hairball clearing dummy read.
ADCSRA |= (1<<ADSC); // do single conversion
And we wait till the conversion is complete.
while(!(ADCSRA & 0x10));//wait for conversion done, ADIF flag
active
Now we repeat this 8 times for better accuracy.
// do the ADC conversion 8 times for better accuracy
for(i=0;i<8;i++)
{
ADCSRA |= (1<<ADSC); // do single conversion
// wait for conversion done, ADIF flag active
ADC_temp = ADCL; // read out ADCL register
ADC_temp += (ADCH << 8); // read out ADCH register
// accumulate
}
We divide by 8, which conveniently is done by left shifting 3 bits. Weren’t we
lucky that we chose to do 8 samples and save processing time by avoiding a
division?