Temperature Sensing: NTC versus DS18B20
Temperature Sensing: NTC versus DS18B20
Overview
Section titled “Overview”There are two fundamentally different ways to measure temperature: a resistive part plus a voltage divider, or a digital part on a 1-Wire bus. The first is cheap and flexible; the second buys you factory calibration. By the end of this section you will be able to:
- Decide whether a project should use an NTC or a DS18B20, and say where the cost lands
- Wire 1-Wire devices correctly (pull-up, cable length, the parasitic-power trap)
- Read a DS18B20 without blocking the main loop for 750 ms
- Attach several probes to one bus and address each by its ROM code
Prerequisites
Section titled “Prerequisites”Before starting this section, make sure you:
- Completed Section 3 of Chapter 25 (dividers and ADC conversion)
- Have an NTC module and a DS18B20 (a waterproof probe version works too)
- Understand what “resolution is not accuracy” means
Key Concepts
Section titled “Key Concepts”What actually differs between the two routes
Section titled “What actually differs between the two routes”| Aspect | NTC thermistor | DS18B20 |
|---|---|---|
| Part cost | Lowest (cents) | An order of magnitude higher |
| Interface | Analogue, consumes an ADC channel | 1-Wire, consumes one GPIO |
| Accuracy | Depends on your calibration; typically around ±1 °C | Factory calibrated, ±0.5 °C within −10…85 °C |
| Resolution | Set by the ADC (12-bit) | Configurable 9–12 bit; 12 bit ≈ 0.0625 °C |
| Range | Part dependent, commonly −40…125 °C | −55…+125 °C |
| Multi-point | One ADC channel per point — runs out fast | Many devices on one line, addressed by ROM |
| Calibration effort | Two-point or multi-point needed; B-value is an approximation | None |
| Noise immunity | High-impedance node, hates long wires | Digital timing, hates weak pull-ups and interrupt storms |
| Power-loss behaviour | Stateless, readable immediately | A read during conversion yields a stale value or an error |
My decision rule: consumer products, cost-sensitive, ±1 °C is fine → NTC. Production equipment, temperature figures that appear in an acceptance report, or multi-point sensing (battery packs, cabinets, tanks) → DS18B20, or go straight to a digital I2C part such as SHT3x.
The reasoning is practical: the NTC error budget is assembled by you — B-value batch spread, divider resistor drift, ADC non-linearity, self-heating. Stack those up and holding ±1 °C without a calibration step is hard. If you cannot hold ±1 °C, then writing “temperature monitoring” into a quotation becomes a verbal promise rather than a spec.
Three real constraints on NTC designs
Section titled “Three real constraints on NTC designs”- Self-heating: keep the excitation current small. With a 10 kΩ fixed resistor, a 10 kΩ NTC and a 3.3 V rail, the loop draws about 165 µA and dissipates roughly 0.13 mW — negligible. Drop the divider to the 1 kΩ region and self-heating can creep past 0.1 °C.
- Leads and parasitic capacitance: once probe wiring exceeds tens of centimetres, the high-impedance node couples noise; add 100 nF close to the analogue pin, and think about layout so the sensitive node stays short. For liquids or condensing environments, choose a stainless waterproof probe rather than letting condensation sit on the bare bead.
- Non-linearity: the B-value equation is an approximation and the error grows at both ends of the range. For full-range use, switch to the manufacturer’s resistance-vs-temperature table or a multi-point fit.
Four things you must get right on DS18B20
Section titled “Four things you must get right on DS18B20”1. The pull-up. The data line needs a 4.7 kΩ pull-up to VDD. Anything larger than about 10 kΩ, longer cables, or several devices slow the rising edge until you start seeing “device not found” intermittently. This is the single most common failure I see.
2. Conversion time. At 12-bit resolution conversion takes roughly 750 ms. Writing delay(750) freezes everything else — MQTT keep-alive and other sampling included. Correct approach: issue the conversion command, return immediately, keep the main loop running, and read back after the interval:
- call
requestTemperatures()→ returns at once - track 800 ms with
millis()in the main loop - read the value only when the window has elapsed
3. Do not rely on parasitic power. The DS18B20 can draw power from the data line, but the conversion current drops the pull-up voltage and the failure rate climbs with cable length and device count. In products, connect all three wires — VDD, GND, DATA. Do not save that one wire.
4. Validate the value. The scratchpad carries a CRC and libraries usually check it, but a library check is not an application check: a disconnected probe often returns a sentinel such as −127, which still has to be filtered in your own logic.
Multi-point sensing: several probes on one bus
Section titled “Multi-point sensing: several probes on one bus”Every DS18B20 has a unique 64-bit ROM address, so:
- On first bring-up, run a device search once, store all addresses, and persist them (flash, or compile-time constants)
- Each cycle: Skip ROM to start conversions → wait → select each ROM address and read its temperature
- Address order is not guaranteed to match physical layout, so bind each address to a probe label (“cell 1”, “return line”); otherwise swapping wires silently swaps locations
This is exactly where multi-point installations go wrong, and exactly why it belongs in the documentation.
Implementation
Section titled “Implementation”Non-blocking DS18B20 reads
Section titled “Non-blocking DS18B20 reads”#include <DallasTemperature.h>#include <OneWire.h>
const uint8_t ONEWIRE_PIN = 4;
OneWire oneWire(ONEWIRE_PIN);DallasTemperature sensors(&oneWire);
const unsigned long CONVERSION_MS = 800; // ~750 ms at 12-bit, with marginunsigned long requestedAt = 0;bool waiting = false;
void setup() { Serial.begin(115200); sensors.begin(); Serial.printf("devices on 1-Wire: %d\n", sensors.getDeviceCount()); sensors.setResolution(12); sensors.setWaitForConversion(false); // the key line: never block inside the library sensors.requestTemperatures(); requestedAt = millis(); waiting = true;}
void loop() { if (waiting && millis() - requestedAt >= CONVERSION_MS) { for (uint8_t i = 0; i < sensors.getDeviceCount(); i++) { float t = sensors.getTempCByIndex(i); // DEVICE_DISCONNECTED_C is the library's sentinel value — filter it explicitly if (t == DEVICE_DISCONNECTED_C || isnan(t) || t < -55.0f || t > 125.0f) { Serial.printf("probe %d: invalid (wiring or not responding)\n", i); continue; } Serial.printf("probe %d: %.2f C\n", i, t); } sensors.requestTemperatures(); // start the next conversion right away requestedAt = millis(); } // Wi-Fi, MQTT and button scanning keep running here — the bus does not stall the loop}Listing the address of every probe
Section titled “Listing the address of every probe”void printProbes() { DeviceAddress da; for (uint8_t i = 0; i < sensors.getDeviceCount(); i++) { sensors.getAddress(da, i); Serial.printf("index %d = {%d,%d,%d,%d,%d,%d,%d,%d}\n", i, da[0], da[1], da[2], da[3], da[4], da[5], da[6], da[7]); }}Copy this address table into the wiring sheet and attach a label to each address — it is the only reliable correspondence in a multi-probe installation.
Sticking with NTC: bake in your calibration result
Section titled “Sticking with NTC: bake in your calibration result”If you do use an NTC, at least perform a two-point calibration and put the correction in code rather than eyeballing it:
float ntcCalibrated() { float raw = ntcTemperatureC(); // the formula from Section 3 // Linear correction measured on our bench (example: 1.6 °C low, slope 1.03) return raw * 1.03f + 1.6f;}Those coefficients come from your own measurements, not from a template. Never publish an accuracy claim for an uncalibrated NTC.
Verification
Section titled “Verification”DS18B20 checks
Section titled “DS18B20 checks”| Check | Expected result | Verified |
|---|---|---|
| Device count at boot | Matches the number of probes wired | |
| Held in the hand for 30 s | Monotonic rise towards skin temperature (32–35 °C) | |
| Ice-water mixture | 0 °C ±0.5 °C | |
| Unplug the data line | Returns DEVICE_DISCONNECTED_C, not 0 °C |
|
| 12-bit sampling cadence | Main loop not blocked (other tasks keep running) | |
| Swap two probes’ wiring | Index and temperature still follow the stored addresses |
NTC checks
Section titled “NTC checks”| Check | Expected result | Verified |
|---|---|---|
| Side-by-side with a DS18B20 | A stable offset that can become a correction coefficient | |
| Ice water at 0 °C | Record the deviation as calibration point one | |
| Change the divider (10 k → 4.7 k) | Readings shift with the operating point, proving where resolution concentrates |
Do not skip the last one: changing the divider moves the useful resolution window, and only after that do you know whether your design is adequate in the temperature band you actually care about.
Troubleshooting
Section titled “Troubleshooting”Issue 1: DS18B20 keeps returning −127 or 85 °C
Section titled “Issue 1: DS18B20 keeps returning −127 or 85 °C”Symptoms: device count reads zero, or the value is stuck at 85 °C (the power-on default).
Possible causes:
- No pull-up on the data line, or one that is far too large (>10 kΩ)
- VDD and GND reversed (this usually heats up — power off immediately)
- 85 °C means the scratchpad was read before a successful conversion ever happened
Solutions:
- Add a 4.7 kΩ pull-up to 3.3 V and re-check the device count
- Look at reset/present pulses with a scope or analyser; absence means wiring or supply
- Enforce the sequence:
requestTemperatures()→ wait at least 750 ms → read
Issue 2: one read stalls the loop, or things break once Wi-Fi joins in
Section titled “Issue 2: one read stalls the loop, or things break once Wi-Fi joins in”Symptoms: the main loop pauses after requestTemperatures(), or readings become corrupt when Wi-Fi/MQTT run concurrently.
Possible causes:
- The library blocks while waiting for conversion (
setWaitForConversion(true)) - 1-Wire bit-banging depends on microsecond timing, which Wi-Fi interrupts can corrupt
Solutions:
- Set non-blocking explicitly:
setWaitForConversion(false)and time 800 ms yourself - Retry once or twice before declaring the sensor dead
- Slow the cadence to 1–2 s; temperature is a slow variable, and winning a few hundred milliseconds buys nothing
Issue 3: one probe of several fails intermittently
Section titled “Issue 3: one probe of several fails intermittently”Symptoms: with three probes, the one furthest from the controller drops out regularly.
Possible causes:
- Bus capacitance grows with cable length, the rising edge degrades, and the furthest device’s presence pulse is missed
- Supply is being fed back from the far end, so its VDD sags
- Parasitic powering cannot supply enough current
Solutions:
- Lower the pull-up to 2.2–4.7 kΩ, shorten stubs, and use proper three-wire connections with a real VDD
- Beyond roughly 5 m, change architecture: acquire locally on a small board and return data over RS485/CAN instead of stretching 1-Wire
- Encode retry counts and “alert only after N consecutive failures” so flapping does not spam the dashboard
Issue 4: NTC readings drift, clearly higher in the afternoon
Section titled “Issue 4: NTC readings drift, clearly higher in the afternoon”Symptoms: at one location the reading tracks sunlight or cabinet temperature, changing faster than the object under test.
Possible causes: the probe senses ambient air rather than the target medium, or it is influenced by radiation and airflow.
Solutions:
- Clamp the probe to the surface, add thermal pad or a metal strap, pot it in place if needed
- Add thermal shielding; keep it off direct sun and radiant sources
- State in the documentation that “this measures the probe temperature” — customers need this to interpret the error band
Best Practices
Section titled “Best Practices”- Do: for production gear, prefer calibrated digital parts (DS18B20, SHT3x) and move calibration risk out of the delivery chain
- Do: always run 1-Wire with three conductors plus a 4.7 kΩ pull-up; skip parasitic power
- Do: sample temperature every 1–2 s with non-blocking conversion so the main loop stays responsive
- Do: keep the address table and probe labels together in the wiring sheet, so swapped wiring shows up as swapped locations
- Don’t: publish an accuracy figure for an uncalibrated NTC
- Don’t: use
delay(750)to wait for conversion — it is the root cause of every real-time problem that follows - Don’t: stretch a 1-Wire bus tens of metres to save one board; reliability fails first
Summary
Section titled “Summary”Key points of this section:
- The trade-off is calibration effort versus component cost: NTC is cheap but you assemble the error budget; DS18B20 costs more but ships calibrated
- Four 1-Wire essentials: 4.7 kΩ pull-up, non-blocking 750 ms conversion, no parasitic power, filter the library’s sentinel values
- Multi-point works through ROM addresses, and each address must be bound to a probe label or wiring changes silently mix up your data
- NTC demands attention to self-heating, lead noise and non-linearity; changing the divider changes where resolution concentrates
- Codify retries and alarm suppression — an intermittent failure is not a dead sensor
Next section: combined temperature/humidity parts (DHT11 and DHT22), and why I prefer an I2C SHT3x in products.
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.
First published attutorial.imagrove.com/sensor-module-selection/04-temperature-sensing-ntc-versus-ds18b20/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.
© Imagrove · ESP32 IoT Tutorial