13.14 Battery sensing
The car should stop before its 3S LiPo is discharged too far, and for that the ESP32 must know the pack voltage. An analog input reads only up to about 3 V, and a full pack gives 12.6 V, which would destroy the pin. Two resistors in series, a voltage divider, scale the pack voltage down to a fraction the pin can take.
The divider
Figure 13.14.1 shows the circuit: a resistor \(R_1\) from the battery to the midpoint, a resistor \(R_2\) from the midpoint to ground, and a voltmeter on the midpoint. Drag the Supply voltage slider and watch the midpoint follow it, always at the same fraction of the supply.
The same current flows through both resistors, so the battery voltage divides between them in proportion to their resistances (the voltage budget again). The midpoint voltage is
\[ V_\text{out} = V_\text{in}\,\frac{R_2}{R_1 + R_2}. \tag{13.14.1}\]
With \(R_1 = 33\) kΩ and \(R_2 = 10\) kΩ the fraction is \(10/43 = 0.233\), and a full battery at 12.6 V gives \(12.6 \cdot 0.233 = 2.93\) V at the midpoint, just inside the range of the pin.
The real divider
The resistors in the kit are ±5 % parts (the gold band, see the series resistor). A “33 kΩ” resistor can be anything from 31.35 kΩ to 34.65 kΩ, and a “10 kΩ” one anything from 9.5 kΩ to 10.5 kΩ. Move the two lower sliders in Figure 13.14.1 to their ends and the midpoint at 12.6 V ranges from 2.71 V to 3.16 V. The upper value is beyond the range in which the ESP32 measures reliably, and the lower one would make every battery reading 7 % too low. Neither mistake shows up on paper.
The pin side is no better. The ESP32’s analog-to-digital converter has a gain that varies by several percent from chip to chip (The converter). So the chain from battery to number has two uncertain links, and we do not try to predict it. We measure it: first the resistors, then the midpoint with the multimeter, and finally the number the ESP32 reports at two known battery voltages. The last step is called calibration, and it absorbs every error of the chain at once.
Step 1: Measure the resistors
Measure both resistors with the ohmmeter before they go into the board, and log the values. Put the measured values into 13.14.1 and predict the midpoint at 12.00 V. If the 33 kΩ resistor reads 32.8 kΩ and the 10 kΩ one 10.06 kΩ, the prediction is \(12.00 \cdot 10.06/42.86 = 2.82\) V, against 2.79 V from the nominal values.
Step 2: Build on the bench supply
Build the divider on the breadboard and feed it from the lab supply at 12.00 V with a current limit of 10 mA (the divider draws 0.3 mA). The midpoint is not connected to the ESP32 yet.
Measure the midpoint against the − rail and compare with the prediction from Step 1. The two should agree to within about 1 %, the accuracy of the ohmmeter and the voltmeter together.
The divider only protects the pin when the resistors are in the right places. Swap them, 10 kΩ on top and 33 kΩ to ground, and the same formula gives \(12.6 \cdot 33/43 = 9.67\) V on an input made for at most 3.3 V. The pin, or the whole chip, may not survive. So the midpoint is measured, at the highest voltage the battery can have, before its wire goes to the ESP32. It must read below 3.0 V at 12.6 V. Measure again after every change to the wiring.
On the car the divider hangs on the car rail after the main switch (Figure 13.14.3), so it is dead when the car is switched off and does not drain the battery on the shelf. It draws \(12.6/43\,000\) A = 0.29 mA when the car is on, which a 2200 mAh pack would need over 7000 hours to empty. The 100 nF capacitor in the figure is optional. It keeps the reading steady, and Loading of a divider explains why; without it, the averaging in the firmware smooths the noise instead.
Calibrating with two points
Between the ends of its range the converter is close to linear, and the divider is linear anyway, so the whole chain from battery voltage to reading is a straight line. Two points fix it, as for the pot in From reading to voltage, and map() carries every other reading along the same line. Only the place of the meter changes: the known voltages are now measured at the divider input, so map() returns the battery voltage in millivolts, and the divider ratio and the errors of both resistors are part of the line.
We set the bench supply to two voltages, measured with the multimeter at the divider input, not read off the supply’s display, and note the average reading at each. Suppose the monitor shows 2680 at 9.00 V and 3745 at 12.60 V. A later reading of 3200 then means
\[ 9000 + (3200 - 2680)\,\frac{12\,600 - 9000}{3745 - 2680}~\text{mV} = 9000 + 520 \cdot \frac{3600}{1065}~\text{mV} = 10\,757~\text{mV}. \]
The measured line rises by \(3600/1065 = 3.380\) mV per count. Nominal resistors and an ideal converter with 4095 counts at 3.3 V would give \((3.3/4095)\cdot(43/10) = 3.465\) mV per count, about 2.5 % more, and Figure 13.14.4 shows how far apart the two lines are. Without calibration this board would report about 0.3 V too much at the cutoff and stop the car too late.
After calibrating, check a third voltage near the cutoff, such as 9.6 V. If the monitor is off by more than about 0.05 V there, move the upper calibration point down to 11.1 V, so that the line runs through the region where the decisions are made.
Build and calibrate the battery monitor
The battery monitor is the PlatformIO project code/battery/ with two source files. battery.h holds everything about the battery: the pin, the calibration, the levels, the filter and the state. main.cpp is a small test program around it. The car program includes the same battery.h.
Flash the battery monitor from Chrome or Edge, without PlatformIO, and watch its readings in the page’s serial monitor. It uses the calibration of the ideal divider, so the voltage it prints is only roughly right; the calibration below is what makes it accurate.
The platformio.ini is the plain file of the PlatformIO chapter. src/battery.h starts with the numbers. Until we have measured our own chain, the calibration is that of the ideal divider and converter:
// battery.h: the 3S battery, read through a voltage divider. The car program includes
// this file unchanged.
#pragma once
#include <Arduino.h>
const int battPin = 34; // divider midpoint, an ADC1 pin
// Calibration: the average reading at two battery voltages from the bench supply.
// These numbers belong to the ideal divider and converter. Put in your own.
const int raw1 = 2597, mV1 = 9000;
const int raw2 = 3636, mV2 = 12600;
// Levels in millivolts, from the LiPo chapter
const int warnMv = 9900; // 3.3 V per cell
const int cutoffMv = 9600; // 3.2 V per cell
const int recoverMv = 10200; // 3.4 V per cell: WARN ends only above this
enum BattState { BATT_OK, BATT_WARN, BATT_CUTOFF };
const char* battStateName[] = {"OK", "WARN", "CUTOFF"};
float battAvg = 0; // moving average of the readings
BattState battState = BATT_OK;
unsigned long lastSampleMs = 0;
unsigned long notLowMs = 0; // the last time the voltage was not below the next level
// The battery voltage in millivolts: the straight line through the two calibration points
int batteryMv() { return map(battAvg, raw1, raw2, mV1, mV2); }
BattState levelOf(int mv) {
if (mv < cutoffMv) return BATT_CUTOFF;
if (mv < warnMv) return BATT_WARN;
return BATT_OK;
}
void batteryBegin() {
analogSetPinAttenuation(battPin, ADC_11db); // the widest input range
battAvg = analogRead(battPin); // start the average at the first reading
battState = levelOf(batteryMv());
}
// Call in every pass of loop(). It reads the pin every 10 ms.
void batteryUpdate() {
if (millis() - lastSampleMs < 10) return;
lastSampleMs = millis();
battAvg = battAvg + (analogRead(battPin) - battAvg) / 32; // 1/32 of the way to the new reading
int mv = batteryMv();
// Down a level only after one second below it, so a dip under load does not count
if (levelOf(mv) > battState) {
if (millis() - notLowMs >= 1000) battState = levelOf(mv);
} else {
notLowMs = millis();
}
// Back up only well above the warning level. CUTOFF holds until the ESP32 restarts.
if (battState == BATT_WARN && mv > recoverMv) battState = BATT_OK;
}src/main.cpp prints the average reading, the voltage and the state twice a second:
// main.cpp: test program for battery.h. Prints the average reading, the battery
// voltage and the state twice a second.
#include <Arduino.h>
#include "battery.h"
unsigned long lastPrintMs = 0;
void setup() {
Serial.begin(115200);
batteryBegin();
}
void loop() {
batteryUpdate();
if (millis() - lastPrintMs < 500) return;
lastPrintMs = millis();
Serial.printf("avg %d %d mV %s\n", (int)battAvg, batteryMv(), battStateName[battState]);
}Calibrate on the bench, with the divider that will go into the car and the ESP32 that will read it. The ESP32 is powered from USB during calibration and nothing is connected to its VIN pin.
- Build the divider on the breadboard: 33 kΩ from the supply input to the midpoint, 10 kΩ from the midpoint to ground, and, if you have one, 100 nF from the midpoint to ground. Leave the midpoint wire loose.
- Set the bench supply to 12.6 V with a current limit of 50 mA and connect it to the divider. Measure the midpoint with the multimeter: about 2.9 V. Do not continue otherwise.
- Connect the supply’s negative terminal to an ESP32
GNDpin and the midpoint to GPIO 34. - Upload the project and open the Serial Monitor.
- Set the supply to 9.00 V, checked with the multimeter at the divider input. Wait for
avgto settle and note it asraw1. - Set the supply to 12.60 V and note
avgasraw2. - Enter the two readings in
battery.h(mV1 = 9000andmV2 = 12600stay) and upload again. - Set the supply to 9.6, 9.9 and 11.1 V in turn and compare the printed voltage with the multimeter. They should agree within 50 mV.
- Turn the supply slowly down from 11 V to 9.8 V and back up. The state should change to
WARNabout one second after the voltage crossed 9.9 V and return toOKonly above 10.2 V. Then go down to 9.4 V:CUTOFFfollows after one second and stays, whatever the supply does, until theENbutton restarts the ESP32.
With the example calibration, the output looks like this as the voltage falls through the warning level. WARN appears one second after the voltage went below 9900 mV:
avg 2950 9912 mV OK
avg 2948 9905 mV OK
avg 2946 9899 mV OK
avg 2944 9892 mV OK
avg 2942 9885 mV WARN
The calibration belongs to that ESP32 and that pair of resistors. If either is replaced, the calibration must be repeated. In the car, the divider is wired as in Figure 13.14.3, and the bench supply connects to the car rail in place of the battery when we want to check the calibration again.
How the monitor works
Loading of a divider
13.14.1 assumed that nothing draws current from the tap. Anything connected there, a multimeter, an ADC pin, a careless wire, appears as a load resistance \(R_L\) in parallel with \(R_2\), and the output drops to
\[ V_\text{out} = V_\text{in}\,\frac{R_2 \parallel R_L}{R_1 + R_2 \parallel R_L}, \qquad R_2 \parallel R_L = \frac{R_2 R_L}{R_2 + R_L}. \]
A convenient way to judge how much a load matters is to replace the divider by its Thévenin equivalent: an ideal source of the unloaded voltage \(V_\text{in} R_2/(R_1+R_2)\) behind the resistance \(R_\text{th} = R_1 \parallel R_2\). A load current \(I_L\) then lowers the output by \(I_L R_\text{th}\). The ESP32 input leaks at most 50 nA (datasheet Table 5-3), so its steady error is \(50\ \text{nA}\cdot R_\text{th}\), negligible for any \(R_\text{th}\) below a few hundred kΩ. For the car’s divider, \(R_\text{th} = 33 \parallel 10~\text{k}\Omega = 7.7~\text{k}\Omega\) (Figure 13.14.5).
The ADC is not a steady load, though. At each conversion it connects a small sampling capacitor to the pin and charges it from the source. Through a large \(R_\text{th}\) that charge arrives slowly, the conversion sees a voltage that has not settled, and the reading comes out low and noisy. A high-resistance node also picks up interference more easily, and on the car there is a lot of it: the motor driver switches 10 A or more at 20 kHz a few centimetres away.
The remedy, optional but cheap, is a capacitor of about 100 nF from the tap to ground, close to the pin. It holds the voltage while the sampling capacitor draws its charge, and together with \(R_\text{th}\) it forms a low-pass filter that removes switching noise. Espressif specifies the ADC’s linearity with exactly such a 100 nF capacitor on the input (datasheet Table 4-3). The filter’s time constant \(\tau = R_\text{th} C = 7.7~\text{k}\Omega \cdot 100~\text{nF} = 0.77\) ms must stay short compared with how fast the measured voltage changes, which for a battery is easy.
Choosing the resistances is therefore a compromise. Small resistors give a stiff, quiet node but draw current from the battery all the time and heat themselves. Large resistors save the battery but make the node soft. For a battery divider read a few times per second, a total of a few tens of kΩ with a 100 nF capacitor works well on the car, where the 3S pack holds thousands of mAh. A small battery that must last for weeks, like the remote’s, justifies a few hundred kΩ.
Filtering the readings
batteryUpdate() is called in every pass of loop(), but it reads the pin only every 10 ms (Waiting without delay()), so the filter behaves the same however fast the loop runs. Each reading updates battAvg with the exponential moving average of Filtering the readings at \(N = 32\). Its time constant is about \(32 \cdot 10~\text{ms} = 0.32\) s: short enough to follow a battery, long enough to ignore a single bad sample. batteryBegin() starts the average at the first reading, so the first printed value is already close.
The low-voltage cutoff with hysteresis
We warn at 9.9 V (3.3 V per cell) and cut off at 9.6 V (3.2 V per cell). These are voltages under load. The voltage at the pack’s terminals sags while the motor draws current and recovers when it stops (Internal resistance and voltage sag): a motor start pulls even a half-empty pack below 9.6 V for a moment. Figure 13.14.6 runs the monitor on a drive with such dips.
batteryUpdate() ported line by line to Python and run on a computed drive: the rest voltage falls slowly, the rail sags by \(I \cdot 0.06~\Omega\) at 5 A while driving, at 30 A during starts and at 12 A during a three-second pull. The motor stops once the state is CUTOFF. The band shows the state.
A single threshold would make the state flicker every time the voltage hovers around it, and the car would stutter. batteryUpdate() avoids this in two ways. A lower state is entered only when the averaged voltage has stayed below its level for one second, so a short dip during acceleration does not count. notLowMs remembers the last time the voltage was not below the next level, and the state drops once that moment lies a second back. A higher state is entered only above recoverMv (10.2 V, 3.4 V per cell), well above the level that caused the change. The gap between the level that enters a state and the level that leaves it is called hysteresis. Between 9.9 and 10.2 V the state depends on where the voltage came from: a pack falling from full is still OK at 10.0 V, while a pack that has already given a warning stays in WARN.
CUTOFF has no way back. After a cutoff the motor stops, the sag disappears and the rest voltage may well climb above 10.2 V, which would let the car drive into the next cutoff. So the state holds until the ESP32 restarts. What to do in each state, limit the throttle in WARN and stop the motor in CUTOFF, belongs to the car program; the monitor only reports.
The 1S divider on the XIAO remote
The hand-held remote runs on a XIAO ESP32-S3 powered by a single LiPo cell, 4.20 V when full. The ESP32-S3 measures 0 to about 3.1 V at 11 dB attenuation (ESP-IDF v4.4, ESP32-S3), so the cell also needs a divider, and the XIAO has no built-in one on the standard board. With \(R_1 = R_2 = 200\) kΩ the ratio is exactly one half:
\[ V_\text{pin}(4.20\ \text{V}) = 2.10\ \text{V}, \qquad V_\text{pin}(3.70\ \text{V}) = 1.85\ \text{V}, \qquad V_\text{pin}(3.30\ \text{V}) = 1.65\ \text{V}. \]
BAT, − and +, at the right.
The resistors are large on purpose. The divider is soldered to the battery pad (Figure 13.14.7) and draws \(4.2/400\,000 = 10.5\ \mu\)A whenever a cell is connected, which empties a 400 mAh cell only after several years. The price is a Thévenin resistance of \(200 \parallel 200 = 100\) kΩ, more than ten times that of the car’s divider, so the 100 nF capacitor at the pin matters even more here (\(\tau = 10\) ms). The midpoint goes to A0 (labelled D0 on the board, GPIO 1).
Calibration follows the same two-point method with 3.30 and 4.20 V from the bench supply, before the divider is soldered to the XIAO. The XIAO’s built-in charger drives the battery pad whenever USB is connected, and it would fight the bench supply if the divider were already attached. Never set the supply above 4.20 V. Once in place, the reading shows close to 4.2 V while the cell is charging, whatever its real state.
Exercises
- In the Falstad circuit simulator, build a 12.6 V source, 33 kΩ from it to a node, and 10 kΩ from the node to ground. Read the node voltage. Then add a load resistor from the node to ground and lower it from 1 MΩ to 10 kΩ. At what load resistance has the node voltage dropped by 1 %? Compare with the Thévenin estimate \(R_L \approx 99\, R_\text{th}\).
- Redesign the 3S divider with \(R_1 = 47\) kΩ and \(R_2 = 10\) kΩ. Compute the pin voltage at 12.6 V and at 9.6 V, the current and the Thévenin resistance. Which property of the converter does this design avoid, and what does it give up?
- A group calibrates and gets 2702 at 9.00 V and 3790 at 12.60 V. Which averaged readings should trip the warning and the cutoff? Put the numbers into
battery.hand check them with the bench supply.