13.11 Reading an analog signal
Many sensors report a quantity as a voltage: a throttle as the angle of a knob, a battery monitor as a fraction of the pack voltage, a joystick as two angles. The simplest of them is the potentiometer, a knob whose angle sets a voltage. We get to know one with the multimeter, then power it from the lab supply and measure its output, and only when we know what it does do we connect it to the ESP32 and plot what the board reads.
The potentiometer
The pot in the kit is marked B10K. Inside it a resistive track of 10 kΩ runs in an arc between the two outer pins, 1 and 3, and a sliding contact, the wipersv. släpkontakt, touches the track wherever the shaft puts it. The wiper is the middle pin, 2. The letter gives the taper, how resistance follows angle: B is linear, so half a turn of the knob puts the wiper half way along the track. An A pot is logarithmic, made for volume knobs, and does not suit a sensor.
Seen from the shaft with the pins pointing down, pin 1 is on the left and pin 3 on the right. Turning the shaft clockwise moves the wiper from pin 1 towards pin 3, over about 300° from one end stop to the other.
Step 1: Measure the pot
Put the pot on the breadboard with its three pins in three separate strips, as in Figure 13.11.1, and set the meter to Ω, on a range above 10 kΩ. The pot is not powered, as measuring resistance requires.
Across the outer pins the meter reads the whole track. Pots are made to a wide tolerance, often ±20 %, so anything from 8 to 12 kΩ is a good pot. Turn the knob: this reading does not change, since the wiper is not part of the path. Write it in the log as \(R\).
Move the red probe to the wiper’s strip. Now the meter reads \(R_{12}\), the part of the track between pin 1 and the wiper, and it follows the knob: close to 0 at the stop on the pin 1 side, close to \(R\) at the other stop, and about \(R/4\) a quarter of the way round. The part between the wiper and pin 3 is the rest, \(R_{23} = R - R_{12}\). Measure it too and check that the two add up to \(R\).
The pot as a voltage divider
With a voltage \(V_s\) across the outer pins, the same current flows through the whole track, and the voltage between pin 1 and the wiper is the share of \(V_s\) that falls across \(R_{12}\),
\[ V_\text{wiper} = V_s\,\frac{R_{12}}{R}. \tag{13.11.1}\]
On a linear pot \(R_{12}/R\) is the fraction of the travel, so the wiper voltage is proportional to the angle of the knob. The circuit is a voltage divider whose two resistors we set with the knob. Figure 13.11.2 has it in Falstad with 3.3 V across the pot. Drag the Knob slider and watch the voltmeter follow it from 0 to 3.3 V.
The voltmeter draws almost nothing, so it does not change the share it measures. The ESP32’s input draws almost nothing too, so the pin will read the same voltage as the meter.
Step 2: Power the pot from the lab supply
We use 3.3 V because the pot will later get its voltage from the ESP32’s 3V3 pin, and the wiper voltage must never exceed what an input pin of the ESP32 can take. Set the bench supply to 3.30 V with the output off, and turn the current limit down to about 10 mA. The pot needs only \(3.3/10\,000~\text{A} = 0.33\) mA. Switch the output on and measure the voltage at the supply’s terminals before anything is connected to them.
Switch the output off again and wire Figure 13.11.3. The red lead goes to the top + rail and the black lead to the bottom − rail. A red jumper takes + down to the strip of pin 3, and a black one runs from the strip of pin 1, past the body of the pot, down to the − rail. Switch the output on. The current display stays at 0.00, since 0.33 mA is below its last digit.
Step 3: Measure the wiper voltage
With the meter on V⎓, put the black probe on the − rail and the red probe in the wiper’s strip (Figure 13.11.3, upper panel). Turn the knob slowly from one stop to the other. The reading runs from 0 V to 3.30 V and passes 1.65 V near the middle of the travel. Stop a quarter of the way from the pin 1 stop and compare the reading with 13.11.1, using \(R\) and \(R_{12}\) from Step 1: for \(R_{12}/R = 0.25\) it is \(3.30 \cdot 0.25 = 0.83\) V. Write both in the log.
Step 4: Swap the ends
Switch the output off, move the two jumpers so that + goes to pin 1 and − to pin 3 (Figure 13.11.3, lower panel), and switch on again. Without touching the knob, the meter now reads 2.47 V, or \(3.30 - 0.83\) V: the wiper is still a quarter of the way from pin 1, but pin 1 is now the high end. Turn the knob clockwise and the voltage falls.
The pot itself has no up and no down. The pin that goes to ground decides which way of turning raises the voltage. A knob that should give more when turned clockwise, the way a volume knob or a throttle does, has pin 1 on ground and pin 3 on the supply. A throttle that runs backwards is fixed by swapping these two wires, not by changing the code.
The wiper is always the output and never goes to the supply. If the supply were across the wiper and an end pin, turning the knob towards that pin would bring the resistance between the supply terminals close to zero. On the lab supply the low current limit catches this; on the ESP32’s 3V3 pin nothing does.
Step 5: Read the pot with the ESP32
Switch the lab supply off and remove its leads and the two jumpers. From now on the ESP32 supplies the 3.3 V. Never connect the lab supply and the ESP32’s 3V3 pin to the same pot: two sources wired together drive current into each other.
The pin rows of the ESP32 DevKit sit 0.9 inch apart and the board is 28 mm wide, so on a single breadboard it covers the holes beside its pins. We use two breadboards side by side, with the rail strip between them removed, and let the ESP32 straddle both (Figure 13.11.4), as in A signal is not a power supply. 3V3 feeds the top + rail and GND the bottom − rail. The pot sits on the lower board with its pins in strips 16 to 20. A red jumper runs from the + rail down to pin 3, a black one from pin 1 to the − rail, and a yellow one from the wiper to D35, which is GPIO 35. GPIO 35 is an input of the converter that keeps working while Wi-Fi runs, and it is the pin the throttle uses on the car (Which pins can read explains the choice).
3V3 feeds the + rail at the top, GND the − rail at the bottom. The pot on the lower board takes + on pin 3 and − on pin 1, and the yellow jumper takes the wiper to D35 (GPIO 35).
The project code/pot/ reads GPIO 35 two hundred times a second and prints each reading:
#include <Arduino.h>
const int potPin = 35; // the wiper of the pot; GPIO 35 is an ADC1 input
const int sampleMs = 5; // 200 readings per second
unsigned long lastMs = 0;
void setup() {
Serial.begin(115200);
analogSetPinAttenuation(potPin, ADC_11db); // the widest input range, up to about 3.1 V
}
void loop() {
if (millis() - lastMs < sampleMs) return; // the next reading is not due yet
lastMs = millis();
int raw = analogRead(potPin); // the converter's number, 0 to 4095
Serial.print(">raw:"); // Teleplot plots every line that starts with >
Serial.println(raw);
}Plot the signal
A column of numbers scrolling past hides what a signal does; a plot shows it. Teleplot plots every line the board prints in the form >name:value, one chart per name, and lists all other lines in a console beside the charts.
Upload the program to a copy of blink. Stop the Serial Monitor, since Teleplot needs the port for itself, click Teleplot in the status bar, choose the COM port and 115200 at the top left of the Teleplot tab and click Open. The chart raw starts to run. Turn the knob and it follows.
What the ESP32 reports
analogRead() returns the converter’s own number, a whole number from 0 to 4095 (\(2^{12}\) steps, 12 bits). It is not a voltage. How many millivolts one step is worth differs from chip to chip, and near both ends of the range the converter stops following the input.
The converter
Inside, the converter compares the input with a reference of about 1.1 V, and the reference itself lies between 1.0 and 1.2 V depending on the chip (ESP-IDF v4.4 ADC documentation). To measure larger voltages, an attenuator in front of the converter scales the input down. Arduino-ESP32 3 uses the strongest setting, ADC_11db, by default, and the pot program sets it anyway with analogSetPinAttenuation() so that it does not depend on the default. ESP-IDF 5 calls the same setting ADC_ATTEN_DB_12, closer to its true value.
How far up 11 dB reaches depends on how much error we accept. The ESP32 datasheet (v5.3, Table 4-4) gives an effective measurement range of 150 to 2450 mV with a total error of ±60 mV, and warns that accuracy is worse above about 3000 counts. The Arduino-ESP32 documentation lists 150 to 3100 mV for the same setting. Both are right: the converter responds up to about 3.1 V, but its characteristic bends near both ends. Below about 0.15 V the reading stays at or near 0, and towards the top it flattens and reaches 4095 before the input reaches 3.3 V. A pot turned to its stops therefore gives no clean 0 and 4095, and code that reads a throttle treats the last few percent at each end as full and a small band around the middle as zero.
Between the ends the response is close to a straight line, but its slope and offset differ from chip to chip by up to about 6 % according to the datasheet. That is why the next section measures two points of the line instead of trusting a nominal conversion.
Which pins can read
The ESP32 has two converters. ADC1 serves GPIO 32 to 39. ADC2 serves GPIO 0, 2, 4, 12 to 15 and 25 to 27, and it is shared with the Wi-Fi radio: while Wi-Fi runs, a read from ADC2 fails. The car runs a Wi-Fi access point, so every analog input on the car uses ADC1. GPIO 34 to 39 are also input-only: they have no output driver and no internal pull-up or pull-down resistors. That makes them poor pins for anything else and good ones for analog inputs, and the car puts its battery divider on GPIO 34 and its throttle pot on GPIO 35.
From reading to voltage: map()
To turn raw into a voltage, we measure the conversion instead of trusting a nominal one. Between the ends the converter is close to linear, so two points fix it: two knob positions at which we read both the meter and raw. Every other reading lies on the straight line through them. For a point \((x_1, y_1)\) and a point \((x_2, y_2)\), a reading \(x\) maps to
\[ y = y_1 + (x - x_1)\,\frac{y_2 - y_1}{x_2 - x_1}. \tag{13.11.2}\]
Arduino has this line built in as map(x, in_min, in_max, out_min, out_max), with \(x_1\) = in_min, \(x_2\) = in_max, \(y_1\) = out_min and \(y_2\) = out_max. It computes (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min in whole numbers, so the division drops the fraction. We therefore map to millivolts, not volts: volts as whole numbers would only know 0, 1, 2 and 3. map() does not stop at the two points either. A reading outside them is carried along the same line, which is right as long as the converter is still linear there.
Example 1: Two measured points
With the pot on the ESP32 as in Figure 13.11.4, the black probe on the − rail and the red probe in the wiper’s strip, we turn the knob until the meter shows about 0.5 V and note both numbers, then do the same at about 2.5 V. Suppose the two points are
| meter | raw |
|
|---|---|---|
| point 1 | 512 mV | 487 |
| point 2 | 2498 mV | 3010 |
Both lie well inside the range where the converter is linear. A later reading of raw = 1748 then gives
\[ y = 512 + (1748 - 487)\,\frac{2498 - 512}{3010 - 487}~\text{mV} = 512 + 1261 \cdot \frac{1986}{2523}~\text{mV} = 1504~\text{mV}, \]
where map() drops the fraction of \(992.6\) before adding 512 (Figure 13.11.5). In the program the two points become constants, and one line converts every reading:
// above setup(): the two measured points
const long raw1 = 487, mV1 = 512; // point 1: raw reading and meter voltage in mV
const long raw2 = 3010, mV2 = 2498; // point 2
// in loop(), after analogRead()
long mV = map(raw, raw1, raw2, mV1, mV2); // the line through the two points
Serial.print(">mV:");
Serial.println(mV);Set the knob anywhere between the two points and compare mV with the meter. They should agree to within a few millivolts. The numbers belong to that ESP32: another board needs its own two points.
map() takes the reading 1748 to 1504 mV.
Filtering the readings
With the knob still, raw jitters by a few counts from one reading to the next. That is noise in the converter, and on a car the motor driver adds more. The datasheet’s advice is to take several readings and average them (notes to Table 4-3). The average that needs only one stored number is the exponential moving average: each new reading \(x\) moves the average \(y\) a fraction \(1/N\) of the way towards itself,
\[ y \leftarrow y + \frac{x - y}{N}. \tag{13.11.3}\]
With \(N = 16\) it smooths about as well as a plain average of the last 16 readings. In the pot program it takes two lines in loop() and one variable above setup():
float avg = 0; // above setup(): the moving average
// in loop(), after analogRead()
avg = avg + (raw - avg) / 16; // 1/16 of the way towards the new reading
Serial.print(">avg:");
Serial.println(avg);The average must be a float. In whole numbers (raw - avg) / 16 is 0 whenever raw lies within 15 counts of the average, and the average would stop short of the signal.
Plot raw and avg together in Teleplot. With the knob still, avg is flat where raw jitters. Turn the knob quickly and avg follows with a delay: after a step it has covered about two thirds of the way in \(N\) readings, here \(16 \cdot 5\) ms = 80 ms. This time constant is the price of the smoothing. A larger \(N\) gives a quieter signal and a slower one, and the right \(N\) depends on how fast the measured quantity really changes. A throttle must follow the hand within a tenth of a second; a battery voltage may take a third of a second, and Battery sensing uses \(N = 32\) at 10 ms.
Exercises
Exercise 1: From reading to angle
Turn the knob to the stop at pin 1 and note raw, then do the same at the stop at pin 3. Use map() with these two readings to turn raw into the angle of the knob, from 0° at the pin 1 stop to 300° at the pin 3 stop. Print it as >angle: and check it with the knob at the middle of its travel.
Exercise 2: The ends of the range
Map out where the converter stops following the input. Turn the knob slowly towards the stop at pin 1 and note the meter’s reading when raw first shows 0. Do the same towards the other stop and note the meter when raw reaches 4095. Then take five more points spread over the travel, each with the meter’s voltage and raw, and plot raw against the voltage. Where is the line straight, and where does it bend? Compare with The converter. Choose the two points of Example 1 from your own plot.
Exercise 3: A throttle that turns the wrong way
Swap the jumpers at pins 1 and 3 and watch the plot. Then put the jumpers back and get the same result in the code instead, with map(). Which of the two would you choose on a car whose wiring is already soldered, and why?
Exercise 4: Smooth or fast
Run the filter of 13.11.3 with \(N\) = 4, 16 and 64 and turn the knob quickly from one stop to the other each time. Read from the Teleplot chart how long avg needs to cover two thirds of the step, and compare with \(N\) times 5 ms. Which \(N\) would you choose for a throttle?
Exercise 5: A joystick axis
The Wokwi potentiometer project reads a pot with analogRead(). Turn the knob to both stops and note the readings. Then write a function that turns the reading of a spring-centred joystick axis into a throttle from \(-100\) to \(100\) percent, with a dead band of ±100 counts around the measured centre and full throttle a little before each end of the travel.