Sensing Battery Voltage with an Arduino


The Arduino already has a built in 10 bit Voltage Sensor on the analog pins. Using the analogRead() function you can read voltages from 0-5 volts in 1024 increments. This gives you a voltage resolution of around 0.005 volts.

The issue is most batteries are above 5 Volts, and the Pilot RC needs at least 6 Volts at the battery terminals to run. If we tried to run the battery directly to the Arduinos analog pin we would break it immediately. So how do you sense voltage greater than 5 Volts?

Voltage Divider

 
VoltageDivider.PNG
 

The Pilot RC has a built in voltage divider that connects the battery to the analog pin of the Arduino. This voltage divider serves two purposes:

1. To limit the current running to the analog pin

2. To divide the voltage by a value of around 6

So if a 12 Volt battery was used at the battery terminals, the Arduino would read a raw value of 2 Volts at the analog pin.

This following example uses the Voltage code that is available on our Downloads page.

The first thing that we need to do is declare the values for our resistors and our Analog Reference. R1 and R2 and fixed values from the resistors that are our the Pilot RC, and vPow is the AREF, or Analog Reference Voltage, that the Arduino is using. Because the 5V regulator delivers a perfect 5V, this value will be 5.0.

float vPow = 5.0;
float r1 = 49900;
float r2 = 10000;

The first thing we want to get is the raw voltage being delivered to the analog pin, which is A4 on the Pilot RC. The Arduino has a 10 bit resolution when reading the analog pins, and gives the values from 0-1023. To convert the analog value to a voltage we use the follow line of code.

v = (analogRead(A4) * vPow) / 1024.0;

Once we have the raw voltage value on the analog pin, we use this formula that will give us the adjusted voltage that the voltage divider is receiving, or the battery voltage.

v2 = v / (r2 / (r1 + r2));

Unfortunately voltage from a battery usually is not completely steady, especially when there is changes in current. To make sure the values are consistent we want to average 100 readings before printing the voltage value of the battery.

vAvg += v2;
vNum++;

  if (vNum == 100) {
    rcV = vAvg/100;
    Serial.print("Voltage: "); 
    Serial.println(rcV);
    vNum=0;
    vAvg=0;
  }

To use this code for your Pilot RC or any other Arduino project, download the code on our Downloads page or in the link above.