How to measure battery voltage from a microcontroller

If they were after the pseudo code then that was a bad question; it all depends on the microcontroller. I probably would have given the candidate the microcontroller's datasheet and observe how he works his way through that 300 pages document.

Anyway, you connect the battery to an ADC input (assumptions: microcontroller has ADC on board and battery voltage is less than microcontroller supply voltage).

  1. Set pin mode for that pin to ADC
  2. Select this ADC input if multiple ADC inputs
  3. Start ADC conversion
  4. Wait for end of conversion flag
  5. read ADC register
  6. calculate Vbat = Vcc x (ADC reading)/(2^ADC resolution)

I think the catch here is that Microcontrollers need an extrenal reference for their A/D. The default reference is the power supply. You can use an external reference, and divide the battery voltage to something below that reference, but that puts a constant drain on the battery which might not be a good idea.

My answer would be: get a shunt-type reference for a voltage that is lower than the battery range of interest. Let's assume a ~5V battery, and a TL431 or the like as 2.5V reference. Now measure the TL431 voltage, using the battery as reference. Assume a 10-bit A/D (most common), that reads N. Now you know that

N * (Battery / 1023) = 2.5

hence

Battery = 2.5 * 1023 / N

If the current drawn by the reference is a problem I would switch its power from an output pin: no power drawn unless we want to do the measurement (which will be a very short period).

=========================================

Now some homework as a preparation for the next interview: You have a USB powered 5V gadet, that has a microcontroller and an LM35 temperature sensor. How would you determine the temperature? Hints: what does the LM35 output, and check the voltage range of a USB outlet. (There is an alternate answer: why the $&^*^& don't you use a digital temperature sensor in the first place?).