Probably everyone, creating their own autonomous robot, wanted to determine the level of battery charge and display them on the display or in the console. This function is mainly necessary for debugging, but in some cases the determination of charge is an important part of the robot's functionality. The difficulty in accomplishing this task is
limiting the maximum input voltage on an analog-to-digital converter (
5V ), as well as huge
jumps in the obtained value. In this post I would like to show my way of reading the voltage from the batteries and determining the charge.
First of all, you need to solder two resistors of
1 kΩ each to this voltage divider circuit:

Thus, if the output voltage of fully charged batteries does not exceed
10V , then the voltage after the divider will be less than 5V, which means that it will be adequately recognized by the analog-to-digital converter.
')
Now you need to connect the output of the divider to any analog input on the Arduino. In my case, this is the A5 leg. Then we will try to calculate the voltage from the batteries:
void setup() { Serial.begin(9600); pinMode(A5, INPUT); } void loop() { float k = 2; float voltage = k*analogRead(A5); }
It turns out that it is not clear, since we forgot to convert the value to the decimal number system. To do this, divide everything by 1024:
void loop() { float k = 2/1024; float voltage = k*analogRead(A5); }
Now we select with the help of a voltmeter the coefficient at which the voltage will be approximately equal to the real voltage:
float k = 2*1.12; float voltage = k*4.5f/1024*analogRead(A5);
We got a lot of jumping up and down voltage, often not similar to the one required. To correct this error, add low-pass filtering with the smoothing coefficient that is optimal for your project:
void loop() { float k = 2*1.12; float voltage = k*4.5f/1024*analogRead(A5); float chargeLevel_procents; float chargeLevel; float y; int z;
Now it remains to measure the voltage on a fully charged battery and fully discharged. In my case, the difference is exactly 1B.
After that, you need to find the battery charge in percent:
y = A_y / 8.4 * 100; chargeLevel_procents = y; chargeLevel = z;
It remains for us only to translate this into a battery icon (or into small squares, like mine) and output to the console:
if(chargeLevel_procents >= 0 && chargeLevel_procents < 33) { z = 1;
Serial.print("\t Voltage: "); Serial.print(A_y); Serial.print(" V "); Serial.print("\t Charge: "); if(z == 1) { Serial.print("â– "); } else if(z == 2) { Serial.print("â– â– "); } else if(z == 3) { Serial.print("â– â– â– "); } else { Serial.print("ERROR"); } Serial.print("\r\n");
I recommend using PuTTY to view the result, since it supports any encoding, unlike the usual “port monitor” in the Arduino IDE.