ESP32 DS18B20 Dallas Temperature Sensor
The DS18B20 is a digital temperature sensor widely used in microcontroller-based applications. It communicates via the 1-Wire protocol, requiring only one data line (and ground) for communication. This sensor is known for its high accuracy, durability, and versatility, making it ideal for temperature measurement projects.
🔗 Quick Links
🛒 DS18B20 Price
ℹ️ About DS18B20 Dallas Temperature Sensor
The DS18B20 is a high-accuracy digital temperature sensor that communicates using a 1-Wire protocol, requiring only a single data line for operation. It is widely used in industrial, weather monitoring, and IoT applications due to its broad temperature range and configurable resolution.
⚡ Key Features #
- High Accuracy – ±0.5°C in the -10°C to +85°C range.
- Wide Operating Range – Measures from -55°C to +125°C.
- 1-Wire Communication – Requires only one data line + ground, simplifying wiring.
- Configurable Resolution – 9-bit to 12-bit selectable resolution.
- Flexible Power Options – Supports normal & parasite power modes.
- Compact & Easy to Integrate – Available in a TO-92 package for easy mounting.
🔗 Learn more about the DS18B20 sensor.
⚙️ DS18B20 Sensor Technical Specifications
Below you can see the DS18B20 Dallas Temperature Sensor Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.
- Type: environment
- Protocol: 1-Wire bus
- Interface: 1-Wire
- Accuracy: ±0.5°C (from -10°C to +85°C)
- Operating Range: -55°C to +125°C
- Voltage: 3.0V to 5.5V (typical 3.3V)
- Resolution: 9-bit to 12-bit (user-configurable)
- Conversion Time: 93.75ms (12-bit resolution)
- Communication Speed: Up to 16.3 kbps
- Power Modes: Normal and Parasite Power Modes
- Power Consumption: 1mA active, <1µA idle
- Package Type: TO-92 (commonly used), also available in other packages
- Unique Identifier: 64-bit unique ROM code for multi-device systems
🔌 DS18B20 Sensor Pinout
Below you can see the pinout for the DS18B20 Dallas Temperature Sensor. The VCC
pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND
pin is the ground connection and must be connected to the ground of your ESP32!
Pin 1 (GND):
Connects to the ground of the circuit.Pin 2 (DQ):
Serves as the data line for 1-Wire communication and can also supply power in parasite power mode.Pin 3 (VDD):
Provides power to the sensor, typically connected to 3.3V or 5V.
Note: In parasite power mode, Pin 3 (VDD)
is connected to ground, and the sensor derives power from the data line (DQ
).
🧵 DS18B20 Wiring with ESP32
Below you can see the wiring for the DS18B20 Dallas Temperature Sensor with the ESP32. Connect the VCC pin of the sensor to the 3.3V pin on the ESP32 or external power supply for power and the GND pin of the sensor to the GND pin of the ESP32. Depending on the communication protocol of the sensor (e.g., I2C, SPI, UART, or analog), connect the appropriate data and clock or signal pins to compatible GPIO pins on the ESP32, as shown below in the wiring diagram.
DS18B20 Pin 1 (GND):
Connect to the ESP32GND
pin.DS18B20 Pin 2 (DQ):
Connect to an available GPIO pin on the ESP32 (e.g.,GPIO4
). Add a pull-up resistor (typically4.7kΩ
) betweenDQ
andVDD
.DS18B20 Pin 3 (VDD):
Connect to the ESP323.3V
pin (or5V
if using a 5V power source).
Note: If using parasite power mode, connect Pin 3 (VDD)
to GND
, and ensure the pull-up resistor is in place between DQ
and 3.3V
or 5V
.
🛠️ DS18B20 Dallas Temperature Sensor Troubleshooting
This guide outlines a systematic approach to troubleshoot and resolve common problems with the . Start by confirming that the hardware connections are correct, as wiring mistakes are the most frequent cause of issues. If you are sure the connections are correct, follow the below steps to debug common issues.
🌡️ One wire DS18B20 reading +85°C
Issue: The DS18B20 sensor always starts with a default reading of 85°C when it powers on. This happens because it hasn't measured the actual temperature yet, or the temperature conversion has not been completed.
How to Fix It:
- Ensure that your code calls
sensors.requestTemperatures()
to initiate a temperature conversion - Wait for the sensor to complete the conversion. For the highest accuracy (12-bit resolution), this requires a delay of 750 milliseconds. Use
delay(750);
after the command. - After the delay, read the temperature using
sensors.getTempCByIndex(0);
. The value will now reflect the actual temperature.
❄️ DS18B20 Reading of -127°C
Issue: The sensor returns a reading of -127°C, which indicates a communication failure or that the sensor is not detected. This may be caused by wiring issues, an incorrect pull-up resistor value, or a faulty sensor. However, this error could also occur intermittently due to transient issues during communication.
Possible Causes:
- Wiring problems, such as loose or incorrect connections.
- Missing or incorrectly sized pull-up resistor (4.7kΩ is standard).
- Insufficient power supply or grounding issues.
- Sensor damage or faulty hardware.
- Improper GPIO configuration in the code.
Solution:
- Check the sensor's wiring and ensure all connections are secure.
- Ensure a 4.7kΩ pull-up resistor is installed between the data line and VCC (adjust to 3.3kΩ if using 3.3V logic).
- Test the power supply to confirm it falls within the sensor's operating range (3.0V to 5.5V).
- Replace the sensor if hardware issues are suspected.
- Use error handling in your code to retry reading the sensor if a -127°C value is detected
💻 Code Examples
Below you can find code examples of DS18B20 Dallas Temperature Sensor with ESP32 in several frameworks:
If you encounter issues while using the DS18B20 Dallas Temperature Sensor, check the Common Issues Troubleshooting Guide.

ESP32 DS18B20 Arduino IDE Code Example
Fill in your main
Arduino IDE sketch file with the following code to use the DS18B20 Dallas Temperature Sensor:
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to GPIO4 (D2 on many boards)
#define ONE_WIRE_BUS 4
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor library
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(115200);
Serial.println("DS18B20 Temperature Sensor");
// Start the DS18B20 sensor
sensors.begin();
}
void loop() {
// Request temperature readings from the sensor
sensors.requestTemperatures();
// Fetch and print the temperature
float temperatureC = sensors.getTempCByIndex(0);
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println("°C");
// Delay for 2 seconds before taking the next reading
delay(2000);
}
This Arduino sketch interfaces with the DS18B20 temperature sensor using the OneWire protocol. It reads temperature data and prints it to the Serial Monitor.
Library Requirement #
To use this code, install the required libraries:
OneWire Library
- Allows communication with OneWire devices.
- Install via Arduino Library Manager or manually from:
🔗 OneWire Library
DallasTemperature Library
- Simplifies interaction with DS18B20 sensors.
- Install via Arduino Library Manager or from:
🔗 DallasTemperature Library
Code Breakdown #
Setup OneWire Communication
ONE_WIRE_BUS (GPIO4)
defines the data pin for DS18B20.- The
OneWire
instance is passed toDallasTemperature
.
Initialization (
setup()
)- Serial communication starts at 115200 baud.
sensors.begin()
initializes the DS18B20 sensor.
Temperature Reading (
loop()
)sensors.requestTemperatures()
fetches sensor data.sensors.getTempCByIndex(0)
retrieves the temperature in Celsius.- The value is printed to the Serial Monitor.
A 2-second delay ensures stable readings. 🚀
Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.

ESP32 DS18B20 ESP-IDF Code ExampleExample in Espressif IoT Framework (ESP-IDF)
If you're using ESP-IDF to work with the DS18B20 Dallas Temperature Sensor, here's how you can set it up and read data from the sensor. Fill in this code in the main
ESP-IDF file:
#include <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "esp_err.h"
#include "ds18b20.h"
#include "onewire_bus.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define ONE_WIRE_GPIO 4 // Change this to your preferred GPIO pin
#define MAX_DS18B20 2 // Maximum number of DS18B20 sensors
#define DS18B20_CONVERSION_DELAY_MS 750 // Default conversion delay for 12-bit resolution
static const char *TAG = "DS18B20";
void app_main(void) {
// Install the 1-Wire bus
onewire_bus_handle_t bus = NULL;
onewire_bus_config_t bus_config = {
.bus_gpio_num = ONE_WIRE_GPIO,
};
onewire_bus_rmt_config_t rmt_config = {
.max_rx_bytes = 10, // 1-byte ROM command + 8 bytes ROM number + 1 byte device command
};
ESP_ERROR_CHECK(onewire_new_bus_rmt(&bus_config, &rmt_config, &bus));
int ds18b20_device_num = 0;
ds18b20_device_handle_t ds18b20s[MAX_DS18B20];
onewire_device_iter_handle_t iter = NULL;
onewire_device_t next_onewire_device;
esp_err_t search_result = ESP_OK;
// Create 1-Wire device iterator to search for sensors
ESP_ERROR_CHECK(onewire_new_device_iter(bus, &iter));
ESP_LOGI(TAG, "Device iterator created, start searching...");
do {
search_result = onewire_device_iter_get_next(iter, &next_onewire_device);
if (search_result == ESP_OK) {
ds18b20_config_t ds_cfg = {}; // Initialize DS18B20 config
// Check if the device is a DS18B20 sensor
if (ds18b20_new_device(&next_onewire_device, &ds_cfg, &ds18b20s[ds18b20_device_num]) == ESP_OK) {
ESP_LOGI(TAG, "Found DS18B20[%d], address: %016llX", ds18b20_device_num, next_onewire_device.address);
ds18b20_device_num++;
} else {
ESP_LOGW(TAG, "Found unknown device, address: %016llX", next_onewire_device.address);
}
}
} while (search_result != ESP_ERR_NOT_FOUND);
ESP_ERROR_CHECK(onewire_del_device_iter(iter));
ESP_LOGI(TAG, "Searching done, %d DS18B20 device(s) found", ds18b20_device_num);
// Read and print temperature from each detected DS18B20 sensor
while (1) {
for (int i = 0; i < ds18b20_device_num; i++) {
float temperature = 0.0;
if (ds18b20_trigger_temperature_conversion(ds18b20s[i]) == ESP_OK) {
vTaskDelay(pdMS_TO_TICKS(DS18B20_CONVERSION_DELAY_MS)); // Wait for conversion
if (ds18b20_get_temperature(ds18b20s[i], &temperature) == ESP_OK) {
ESP_LOGI(TAG, "DS18B20[%d] Temperature: %.2f°C", i, temperature);
} else {
ESP_LOGE(TAG, "Failed to get temperature from DS18B20[%d]", i);
}
} else {
ESP_LOGE(TAG, "Failed to trigger temperature conversion for DS18B20[%d]", i);
}
}
vTaskDelay(pdMS_TO_TICKS(2000)); // Wait 2 seconds before the next reading
}
}
This ESP-IDF example demonstrates how to interface with the DS18B20 temperature sensor using OneWire communication on an ESP32.
Library Requirements #
To compile and run this code, you must install the required ESP-IDF components:
OneWire Bus Library
- Handles OneWire communication on ESP32 using the RMT peripheral.
- Install via ESP-IDF Component Manager:
idf.py add-dependency "espressif/onewire_bus"
- Or download manually:
🔗 OneWire Bus Library
DS18B20 Driver
- Provides functions to initialize and read data from DS18B20 sensors.
- Install via ESP-IDF Component Manager:
idf.py add-dependency "espressif/ds18b20"
- Or download manually:
🔗 DS18B20 Library
Code Breakdown #
Initialize OneWire Bus
ONE_WIRE_GPIO (GPIO4)
is defined as the data pin.onewire_new_bus_rmt()
sets up OneWire communication using ESP32's RMT peripheral.
Search for DS18B20 Sensors
onewire_new_device_iter()
scans for devices on the bus.- Detected DS18B20 sensors are stored in an array.
Reading Temperature
ds18b20_trigger_temperature_conversion()
starts a measurement.- A 750ms delay ensures accurate readings at 12-bit resolution.
ds18b20_get_temperature()
retrieves the temperature.- The result is logged using
ESP_LOGI()
.
Continuous Monitoring
- The code loops indefinitely, reading sensor data every 2 seconds.
Update the I2C pins (I2C_MASTER_SDA_IO
and I2C_MASTER_SCL_IO
) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.

ESP32 DS18B20 ESPHome Code Example
Fill in this configuration in your ESPHome YAML configuration file (example.yml
) to integrate the DS18B20 Dallas Temperature Sensor
sensor:
- platform: dallas_temp
address: 0x1234567812345628
name: temperature
update_interval: 120s
This ESPHome configuration integrates the Dallas Temperature Sensor (DS18B20) for OneWire communication.
Code Breakdown #
- The configuration defines a sensor with key attributes:
platform
→ Specifies the Dallas platform for DS18B20 sensors.address
→ Unique hardware ID of the sensor.name
→ Custom label for the sensor.update_interval
→ Defines how often temperature readings are updated.
For detailed configuration options, refer to the official ESPHome documentation:
🔗 ESPHome Dallas Temperature Sensor
Upload this code to your ESP32 using the ESPHome dashboard or the esphome run
command.

ESP32 DS18B20 PlatformIO Code Example
For PlatformIO, make sure to configure the platformio.ini
file with the appropriate environment and libraries, and then proceed with the code.
Configure platformio.ini
First, your platformio.ini
should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
paulstoffregen/OneWire @ ^2.3.7
milesburton/DallasTemperature @ ^3.11.0
ESP32 DS18B20 PlatformIO Example Code
Write this code in your PlatformIO project under the src/main.cpp
file to use the DS18B20 Dallas Temperature Sensor:
#include <Arduino.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to GPIO4
#define ONE_WIRE_BUS 4
// Create a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass the oneWire reference to Dallas Temperature
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(115200);
Serial.println("DS18B20 Temperature Sensor with PlatformIO");
// Start the DS18B20 sensor
sensors.begin();
}
void loop() {
// Request temperature measurement
sensors.requestTemperatures();
// Get temperature in Celsius
float temperatureC = sensors.getTempCByIndex(0);
// Print the temperature to the serial monitor
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println("°C");
// Delay for 2 seconds before the next reading
delay(2000);
}
#include
and#include
import the required libraries for 1-Wire communication and DS18B20 sensor handling.#define ONE_WIRE_BUS 4
sets the GPIO pin connected to the DS18B20 data pin.- The
setup()
function initializes serial communication and the DS18B20 sensor withsensors.begin()
. - In the
loop()
function,sensors.requestTemperatures()
requests a temperature measurement. sensors.getTempCByIndex(0)
retrieves the temperature in Celsius, which is printed to the serial monitor usingSerial.print()
.
Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload
command.

ESP32 DS18B20 MicroPython Code Example
Fill in this script in your MicroPython main.py file (main.py
) to integrate the DS18B20 Dallas Temperature Sensor with your ESP32.
import machine
import onewire
import ds18x20
import time
# Define the GPIO pin where the DS18B20 data line is connected
ds_pin = machine.Pin(4)
# Create a OneWire object
ow = onewire.OneWire(ds_pin)
# Create a DS18X20 object
ds = ds18x20.DS18X20(ow)
# Scan for DS18B20 devices on the bus
roms = ds.scan()
print("Found DS18B20 devices:", roms)
while True:
# Request temperature conversion
ds.convert_temp()
time.sleep(1) # Wait for the conversion to complete
# Read temperature from each device
for rom in roms:
temp = ds.read_temp(rom)
print("Temperature:", temp, "°C")
time.sleep(2) # Delay before the next reading
import machine
,import onewire
, andimport ds18x20
are used to handle GPIO pins, 1-Wire protocol, and DS18B20 sensor operations respectively.ds_pin = machine.Pin(4)
sets GPIO4 as the pin connected to the DS18B20 data line.- The
OneWire
andDS18X20
objects are initialized to communicate with the sensor. ds.scan()
searches for DS18B20 sensors connected to the bus and returns their ROM addresses.- Inside a loop,
ds.convert_temp()
starts a temperature measurement, andds.read_temp(rom)
reads the temperature from each sensor. - The temperature readings are printed to the console with
print()
.
Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy
.
Conclusion
We went through technical specifications of DS18B20 Dallas Temperature Sensor, its pinout, connection with ESP32 and DS18B20 Dallas Temperature Sensor code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.