Skip to content

Analog Reading and Voltage Dividers

Analog Reading and Voltage Dividers

Resistive sensing elements (thermistors, photoresistors, gas sensors) do not hand you a voltage — they change resistance. The step that converts resistance into a measurable voltage is the voltage divider. By the end of this section you will be able to:

  • Draw the divider network for any resistive part and derive the conversion formula used in code
  • Configure the ESP32 ADC attenuation correctly and understand why “a reading is not a voltage”
  • Suppress noise with multi-sample filtering
  • Turn an NTC reading into temperature with the B-value equation, and know when not to use it

Before starting this section, make sure you:

  • Completed Sections 1 and 2 of Chapter 25
  • Have a potentiometer or NTC module and a multimeter
  • Know which pins on your board are ADC1 channels

A resistive part wired alone to a GPIO tells you nothing — the ADC measures voltage. It must sit in series with a known resistor, and you sample the midpoint:

VCC ──── Rfixed ────┬──── analog pin
│
device (NTC / LDR / …)
│
GND ────────────────┴──── GND

With the device in the lower leg (towards GND):

  • Vout = VCC × Rdevice / (Rfixed + Rdevice)
  • Inverting it: Rdevice = Rfixed × Vout / (VCC − Vout)

Choose the fixed resistor close to the device resistance at its operating point — 10 kΩ suits a 10 kΩ NTC, which centres the useful range inside the measurement span. Too small wastes power and increases self-heating; too large creates a high-impedance node that picks up noise and gets pulled by the ADC’s own input impedance.

Swapping the two legs is legal, but then “higher reading = lower resistance” and the logic direction flips. Write the orientation into the wiring sheet, otherwise the conversion formula in code will eventually disagree with the circuit.

Aspect Fact Consequence
Resolution 12-bit by default; analogRead() returns 0–4095 You must know the span before converting
Attenuation Arduino core defaults to 11 dB (full scale ≈ 3.1–3.3 V); 0 dB covers only ≈ 1.1 V but is more linear For small low-voltage signals, 0 dB can be measurably better
Non-linearity The original ESP32 ADC is non-linear at both ends, worst near full scale Never reaching 0 or 4095 is normal, not a fault
Reference When the reference follows VDD, any supply ripple moves the reading Use the internal reference or an external ADC when accuracy matters
ADC1 / ADC2 On the original ESP32, ADC2 cannot be used while Wi-Fi is active Plan sampling pins in the ADC1 group (GPIO32–39 family)
Input impedance Nodes above ≈100 kΩ are pulled by the sample-and-hold circuit Keep divider resistors in the kΩ range and add 100 nF at the pin

Takeaway: treating analogRead() as a relative position is safe; treating it as a voltmeter requires one calibration pass with a multimeter first. If you genuinely need accurate voltage, use an ADS1115-class external ADC rather than forcing the on-chip ADC to be something it is not.

From resistance to temperature: the B-value equation

Section titled “From resistance to temperature: the B-value equation”

The common approximation (not the full Steinhart-Hart form):

  • 1/T = 1/T0 + (1/B) × ln(R / R0)
  • T0 = 298.15 K (25 °C), R0 = nominal resistance at 25 °C (usually 10 kΩ), B from the datasheet (often 3950)

It is adequate within the part’s specified range (roughly −20 to 120 °C) and typically gives about 1 °C accuracy. For ±0.5 °C, use a calibrated digital device such as DS18B20 — this is precisely why a digital-output variant beats a bare analogue part.

Battery monitoring: a divider where leakage current must be calculated

Section titled “Battery monitoring: a divider where leakage current must be calculated”

A Li-ion cell (3.0–4.2 V) must be divided down below 3.3 V, and two equal resistors halving the rail is the usual approach:

Resistor pair Current at full charge Deep-sleep budget Noise sensitivity
2 × 10 kΩ ≈ 210 µA Unacceptable on battery products Low
2 × 100 kΩ ≈ 21 µA Common compromise Medium
2 × 1 MΩ ≈ 2.1 µA For ultra-low power High, easily pulled off

The right fix for a low-power product is not “use bigger resistors” but switching the divider branch with a GPIO (only energise it while measuring), or using a monitor IC with a shutdown pin.

Filtered divider reading: voltage first, then resistance

Section titled “Filtered divider reading: voltage first, then resistance”
const uint8_t SENSOR_PIN = 34; // ADC1, usable with Wi-Fi active
const float R_FIXED = 10000.0; // upper leg, 10 kΩ
const float V_DIV = 3.28; // measured supply voltage, not a guessed 3.30
const uint8_t SAMPLES = 9;
// Median filter: robust against spikes, unlike a plain average
float readFiltered() {
uint16_t buf[SAMPLES];
for (uint8_t i = 0; i < SAMPLES; i++) {
buf[i] = analogRead(SENSOR_PIN);
delay(2);
}
for (uint8_t i = 0; i < SAMPLES - 1; i++) {
for (uint8_t j = 0; j < SAMPLES - 1 - i; j++) {
if (buf[j] > buf[j + 1]) { uint16_t t = buf[j]; buf[j] = buf[j + 1]; buf[j] = t; }
}
}
return buf[SAMPLES / 2];
}
float readVoltage() {
return readFiltered() * V_DIV / 4095.0; // 12-bit span normalised to 4095
}
float readDeviceResistance() { // device in the lower leg
float v = readVoltage();
if (v >= V_DIV - 0.01) return -1; // end of range — let the caller decide
return R_FIXED * v / (V_DIV - v);
}
#include <cmath>
const float NTC_R0 = 10000.0; // nominal resistance at 25 °C
const float NTC_B = 3950.0; // B value from the datasheet
const float T0_K = 298.15;
float ntcTemperatureC() {
float r = readDeviceResistance();
if (r < 100.0 || r > 1000000.0) return NAN; // validity gate: open or short
float tK = 1.0 / (1.0 / T0_K + log(r / NTC_R0) / NTC_B);
return tK - 273.15;
}
void setup() { Serial.begin(115200); }
void loop() {
float t = ntcTemperatureC();
Serial.printf("R=%.0f ohm, T=%.2f C\n", readDeviceResistance(), t);
delay(1000);
}

Two points matter: the NAN gate — a disconnected sensor must not return a plausible-looking 25 °C — and V_DIV as a measured value, because 3.28 versus 3.31 V shows up directly in degrees.

bool plausible(float t) {
return !isnan(t) && t > -20.0 && t < 120.0; // bounds from the application, not the component
}

Putting range limits in code rather than in a comment is the highest value-per-line guard in any analogue project.

Build trust with the multimeter before trusting the code.

Check Expected result Measured Verified
Actual supply voltage at the divider Recorded as V_DIV (a measurement, not 3.30)
Potentiometer at 0 % ADC near 0, pin voltage < 50 mV
Potentiometer at 100 % ADC near full scale, pin voltage ≈ V_DIV
Multimeter vs converted voltage Difference < 50 mV; beyond that you hit the non-linear region
Warm the NTC by hand for 30 s Monotonic rise of 3–8 °C, no jumps
Unplug the NTC Returns NAN, not 25 °C

If the ends of travel do not approach 0 and full scale, suspect attenuation setting or supply offset and re-check rows 1 and 4.

Symptoms: whatever you do to the device, the ADC value is fixed.

Possible causes:

  • The pin is not an ADC pin, or not the channel you looked up
  • An ADC2 pin in use while Wi-Fi is connected (original ESP32)
  • The upper leg of the divider is not connected, leaving the pin floating

Solutions:

  1. Re-check the board pin map for ADC channel numbering
  2. Move to an ADC1 pin, or temporarily disable Wi-Fi to confirm the diagnosis
  3. Power off and measure continuity through the divider branch

Issue 2: readings jump by tens or hundreds of counts

Section titled “Issue 2: readings jump by tens or hundreds of counts”

Symptoms: values wander at rest; converted temperature moves more than 1 °C.

Possible causes:

  • Divider resistors in the hundreds of kΩ, so the node impedance is too high
  • No small capacitor at the analogue pin, so charge injection during sampling shows up
  • Supply ripple shared with motors or relays

Solutions:

  1. Drop to the 10 kΩ range and trade a little current for stability
  2. Add a 100 nF capacitor from the signal pin to ground, placed close
  3. Median filtering plus throttled sampling; if it persists, split the analogue supply from the radio/actuator supply, or move to an external ADC

Issue 3: temperature is consistently offset by a few degrees

Section titled “Issue 3: temperature is consistently offset by a few degrees”

Symptoms: the trend is right, the absolute value is not.

Possible causes:

  • V_DIV set to the nominal 3.30 instead of the measured rail
  • R0 / B values that do not match the actual batch
  • The divider resistor’s own temperature coefficient, or the sensor sitting next to a heat source (regulators, MCU)

Solutions:

  1. Measure the rail and hard-code the measured figure
  2. Two-point calibration: one reading in ice water (0 °C), one against a reference thermometer in warm water, then back out the real parameters
  3. Move the NTC away from heat sources and route its leads clear of power areas
  • ✅ Do: measure the actual supply voltage in every analogue project and store it as a code constant — never trust the silkscreen
  • ✅ Do: median filtering kills spikes, averaging kills white noise; for slow variables like temperature, apply both (median then average)
  • ✅ Do: treat NAN plus application-specific bounds as the validity rule — better to report nothing than to report garbage
  • ✅ Do: for production temperature sensing, prefer calibrated digital parts (DS18B20, SHT3x); keep NTC for cost-driven designs
  • ❌ Don’t: build an ESP32 ADC front end with resistors above 100 kΩ
  • ❌ Don’t: leave a battery-sensing divider permanently connected on a low-power product
  • ❌ Don’t: treat the on-chip ADC as a precision voltmeter; add an external ADC when accuracy is the requirement

Key points of this section:

  1. Resistive parts need a divider; pick the fixed resistor near the device’s operating resistance (10 kΩ for a 10 kΩ NTC) and record the leg orientation in the wiring sheet
  2. An ADC reading is relative: 12-bit 0–4095 by default, ≈3.1–3.3 V full scale at the default 11 dB attenuation, non-linear at both ends, and sensitive to supply drift
  3. The conversion chain must be complete and checkable: raw → voltage (measured V_DIV) → resistance → physical unit (B-value equation)
  4. Validity outranks precision: open circuit, short circuit and out-of-range must return NAN rather than a plausible number
  5. Two original-ESP32 traps: ADC2 conflicts with Wi-Fi, and high-impedance nodes get pulled during sampling — re-check the pin map whenever the chip changes

Next section: temperature modules — the trade-off between an NTC and a DS18B20 on a 1-Wire bus.


Building a commercial IoT product?

We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.

💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.

Talk to us →

First published attutorial.imagrove.com/sensor-module-selection/03-analog-reading-and-voltage-dividers/Please credit Imagrove and link back to this page when quoting or republishing.

Questions or issues with this tutorial?

Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.