When integrating environmental monitoring into an embedded project, the DS18B20 remains the industry-standard digital temperatursensor for hobbyists and industrial prototypes alike. Unlike analog thermistors that require voltage dividers and suffer from ADC non-linearity, the DS18B20 outputs a fully calibrated digital signal over a single data wire. However, interfacing this sensor with an ESP32 introduces specific timing and interrupt challenges that do not exist on older 8-bit AVRs. This guide provides the exact wiring, raw-to-unit math, and ESP32-specific debugging steps required to get reliable readings.

The Sensing Principle: How the DS18B20 Measures Heat

The DS18B20 utilizes a silicon bandgap temperature sensing element. In this solid-state mechanism, the voltage difference across two matched transistors operating at different current densities exhibits a highly predictable, linear relationship with absolute temperature. Because the sensor integrates both the sensing element and a 12-bit analog-to-digital converter (ADC) directly onto the silicon die, the microcontroller never has to interpret raw analog voltages.

Instead of outputting a varying voltage or resistance, the sensor's internal logic converts the bandgap measurement into a 16-bit two's complement binary number. This digital value is stored in an internal scratchpad register and transmitted serially via the Dallas 1-Wire protocol when the master (your ESP32) requests it. This architecture eliminates signal degradation over long cable runs, as the data is transmitted as distinct digital high/low pulses rather than a fragile analog voltage.

Wiring and Pinout: ESP32 to DS18B20

The DS18B20 operates in two power modes: external power and parasitic power. For reliable operation on an ESP32—especially when Wi-Fi is active and drawing peak current—always use external power mode. Parasitic power mode relies on the data line to charge an internal capacitor, which frequently sags and causes CRC errors on 3.3V logic systems.

Table 1: DS18B20 External Power Wiring to ESP32
DS18B20 Pin Wire Color (Typical TO-92) Wire Color (Waterproof Probe) ESP32 Connection Notes & Supply Range
1 (GND) Black Black GND Common ground reference
2 (DQ) Yellow / White Yellow / White GPIO 4 (or any) Requires 4.7kΩ pull-up to 3.3V
3 (VDD) Red Red 3V3 Supply range: 3.0V to 5.5V DC
Callout Tip: The Pull-Up Resistor is Non-Negotiable

The 1-Wire protocol uses open-drain communication. The ESP32 and the sensor can only pull the data line LOW; neither can drive it HIGH. You must place a 4.7kΩ resistor between the DQ line and the 3.3V supply. Without it, the line floats, and your ESP32 will read random noise or fail to detect the device entirely.

Output Signal Math and Code Implementation

The output of the DS18B20 is strictly digital. The sensor returns a 16-bit two's complement integer representing the temperature in increments of 0.0625°C (when configured for 12-bit resolution). To convert this raw integer into a physical Celsius value, you divide the raw register value by 16.0.

Raw-to-Unit Math:
If the raw 16-bit value is 0x0550 (1360 in decimal), the math is: 1360 / 16.0 = 85.0°C.
If the temperature is negative, the sensor outputs a two's complement value. For example, 0xFF5E translates to -162 in signed decimal. The math is: -162 / 16.0 = -10.125°C.

Below is the complete, copy-pasteable Arduino framework code for the ESP32. It uses the standard OneWire and DallasTemperature libraries, but includes explicit error handling for the -127 and 85 error states common in embedded deployments.

#include <OneWire.h>
#include <DallasTemperature.h>

// Define the GPIO pin connected to the DS18B20 DQ line
#define ONE_WIRE_BUS 4

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  Serial.begin(115200);
  sensors.begin();
  // Force 12-bit resolution for maximum precision (0.0625°C steps)
  sensors.setResolution(12);
}

void loop() {
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);

  // Error handling for disconnected or unpowered sensors
  if (tempC == -127.0) {
    Serial.println("ERROR: Sensor disconnected or missing pull-up resistor.");
  } else if (tempC == 85.0) {
    Serial.println("WARNING: Read power-on reset default. Increase conversion delay.");
  } else {
    Serial.printf("Temperature: %.4f °C\n", tempC);
  }
  
  delay(2000);
}

Calibration, Scaling, and Interference Sources

From the factory, the DS18B20 is calibrated to ±0.5°C accuracy between -10°C and +85°C. For most HVAC, brewing, or ambient monitoring projects, no user calibration or scaling is required. If your application demands higher precision, you must perform a two-point calibration in software by comparing the sensor's output against a NIST-traceable reference thermometer in an ice bath (0°C) and a boiling water bath (adjusted for your local barometric pressure).

Common Interference Sources on ESP32:

  • Wi-Fi Interrupt Preemption: The 1-Wire protocol relies on strict microsecond timing. On the ESP32, Wi-Fi and Bluetooth background tasks trigger hardware interrupts that can pause the 1-Wire bit-banging routine, resulting in CRC (Cyclic Redundancy Check) failures. Fix: Use a library that leverages the ESP32's RMT (Remote Control) peripheral for hardware-timed 1-Wire communication, or temporarily disable Wi-Fi during the 750ms temperature conversion window.
  • Capacitive Loading on Long Cables: Running a 1-Wire bus beyond 10 meters introduces parasitic capacitance, which rounds off the sharp digital edges required by the protocol. Fix: Use CAT5 twisted-pair cable, dedicate one pair to DQ and GND, and lower the pull-up resistor to 2.2kΩ or 1.0kΩ to charge the line faster.
  • Electromagnetic Interference (EMI): Routing the sensor cable parallel to AC mains wiring will induce noise. While the digital signal is more robust than analog, severe EMI can flip bits during transmission. Fix: Cross AC mains at 90-degree angles and use shielded cable with the shield grounded at the ESP32 end only.

For deeper technical specifications on the silicon bandgap architecture and timing diagrams, refer to the Analog Devices DS18B20 datasheet. For ESP32-specific GPIO and interrupt handling constraints, consult the official Espressif GPIO API Reference.

Frequently Asked Questions

Why is my temperatursensor reading 85°C on startup?

An initial reading of exactly 85°C is not a hardware failure; it is the factory-default power-on reset value stored in the sensor's scratchpad register. This happens when your ESP32 requests the temperature before the sensor has completed its very first analog-to-digital conversion (which takes up to 750ms at 12-bit resolution). To fix this, add a delay(800) immediately after calling sensors.requestTemperatures() in your setup loop, or discard the first reading in your code logic.

Why does my temperatursensor return -127°C?

A reading of -127°C (or sometimes -127.06°C) is the standard error code returned by the DallasTemperature library when the ESP32 cannot find any devices on the 1-Wire bus. This is almost always caused by one of three physical issues: a missing 4.7kΩ pull-up resistor, a broken ground connection, or the DQ and VDD wires being swapped. Verify your wiring with a multimeter; you should read approximately 3.3V between the VDD and GND wires at the sensor end.

Can I use a 3.3V temperatursensor on a 5V Arduino logic pin?

Yes, but you must be careful with the pull-up resistor. If you power the DS18B20 with 3.3V but use a 5V Arduino, you must connect the 4.7kΩ pull-up resistor to the 3.3V rail, not the 5V rail. Pulling the data line up to 5V will backfeed voltage into the sensor's DQ pin through its internal protection diodes, potentially destroying the silicon die or causing erratic readings. Alternatively, power the sensor from the Arduino's 5V pin (since its supply range extends to 5.5V) and use a 5V pull-up.

How far can I run the cable for a 1-Wire temperatursensor?

In a standard external power configuration using CAT5 twisted-pair cable and a 4.7kΩ pull-up resistor, you can reliably run a 1-Wire bus up to 30 meters (100 feet). If you need to push the distance to 100 meters or more, you must lower the pull-up resistor to 1.0kΩ to overcome the cable's parasitic capacitance, use a dedicated 1-Wire master IC (like the DS2480B) instead of software bit-banging, and ensure you are not using parasitic power mode.