ESP32 DS18B20 Dallas Temperature Sensor
Overview
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.
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.
Where to Buy
Prices are subject to change. We earn from qualifying purchases as an Amazon Associate.
Technical Specifications
Pinout Configuration
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
).
Wiring with ESP32
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
.
Troubleshooting Guide
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
Debugging Tips
🔍 Serial Monitor
Use the Serial Monitor to check for error messages and verify the sensor's output. Add debug prints in your code to track the sensor's state.
⚡ Voltage Checks
Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor's requirements.
Additional Resources
Code Examples
Arduino Example
#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. 🚀
ESP-IDF Example
#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.
ESPHome Example
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
PlatformIO Example
platformio.ini
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
paulstoffregen/OneWire @ ^2.3.7
milesburton/DallasTemperature @ ^3.11.0
PlatformIO Example Code
#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 <OneWire.h>
and#include <DallasTemperature.h>
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()
.
MicroPython Example
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()
.
Conclusion
The ESP32 DS18B20 Dallas Temperature Sensor is a powerful environment sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it's a versatile choice for your IoT projects.
For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.
Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.