Electronic – Measuring 32V using ADC of Atmega8

adcavrcmicrocontroller

I'm trying to measure the battery voltage of 30V using the ADC of an AVR Atmega8, AVCC is connected to 5V.

I connected a suitable voltage divider: R1 is 270k, R2 is 10k. The result I get is wrong at all, at 30V I get 23V.
The equation I use is batteryvoltage = 5*1023/adcReading.

// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input)
{
ADMUX=adc_input|ADC_VREF_TYPE;
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}
unsigned int adcReading = 0;

adcReading = read_adc(0);
batteryVoltage = 5*1023/adcReading;

Best Answer

Your calculation for the battery voltage is wrong. Assuming adcReading varies from 0 to 1023, it should look like this:

batteryVoltage = (adcReading * 30) / 1023

Note though that denoting voltage like this, with integer volts, will only give you 31 possible readings (0 to 30). A more useful result might be in millivolts:

batteryVoltageMillivolts = (adcReading * 30000) / 1023

Note that in this case batteryVoltageMillivolts will have to be a long, not an int.