Skip to main content
ESPBoards

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.

Jump to Code Examples

Arduino Core Image
ESP-IDF Image
ESPHome Image
PlatformIO Image
MicroPython Image

Quick Links

DS18B20 Dallas Temperature Sensor Datasheet ButtonDS18B20 Dallas Temperature Sensor Specs ButtonDS18B20 Dallas Temperature Sensor Specs ButtonDS18B20 Dallas Temperature Sensor Specs Button

DS18B20 Price

Normally, the DS18B20 Dallas Temperature Sensor costs around 2$ per Psc.
The prices are subject to change. Check current price:

Amazon com

Amazon de logo

Aliexpress logo

About DS18B20 Dallas Temperature Sensor

The DS18B20 is a digital temperature sensor that operates using a 1-Wire communication protocol, requiring only one data line and ground for operation. It provides high accuracy of ±0.5°C in the range of -10°C to +85°C and supports a wide operating temperature range from -55°C to +125°C. The sensor operates within a voltage range of 3.0V to 5.5V, with a typical voltage of 3.3V, and offers a user-configurable resolution from 9-bit to 12-bit. It supports both normal and parasite power modes, making it versatile for different applications. The DS18B20 is commonly available in a TO-92 package, making it easy to integrate into various projects. 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.

  • 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 ESP32 GND pin.
  • DS18B20 Pin 2 (DQ): Connect to an available GPIO pin on the ESP32 (e.g., GPIO4). Add a pull-up resistor (typically 4.7kΩ) between DQ and VDD.
  • DS18B20 Pin 3 (VDD): Connect to the ESP32 3.3V pin (or 5V 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.

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.

Arduino Core Image

ESP32 DS18B20 Arduino IDE Code Example

Example in Arduino IDE

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);
}

#include and #include import the libraries required for 1-Wire communication and temperature sensor handling.

#define ONE_WIRE_BUS 4 specifies the GPIO pin connected to the data line of the DS18B20 sensor.

The setup() function initializes serial communication and the DS18B20 sensor using sensors.begin().

The loop() function requests temperature readings with sensors.requestTemperatures() and retrieves the value in Celsius using sensors.getTempCByIndex(0). The result is then printed to the serial monitor.

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.

ESP-IDF Image

ESP32 DS18B20 ESP-IDF Code Example
Example 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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "onewire.h"
#include "ds18b20.h"

// Define GPIO for the DS18B20 data line
#define DS18B20_GPIO GPIO_NUM_4

void app_main(void) {
printf("DS18B20 Temperature Sensor with ESP-IDF
");

// Initialize 1-Wire protocol
onewire_bus_handle_t bus = onewire_bus_init(DS18B20_GPIO);

if (bus == NULL) {
printf("Failed to initialize 1-Wire bus
");
return;
}

// Search for devices on the bus
uint8_t rom_code[8];
if (!onewire_search_first(bus, rom_code, false)) {
printf("No DS18B20 sensors found on the bus
");
onewire_bus_deinit(bus);
return;
}

// Display the ROM code of the detected sensor
printf("Found device with ROM: ");
for (int i = 0; i < 8; i++) {
printf("%02X ", rom_code[i]);
}
printf("
");

// Initialize the DS18B20 sensor
if (!ds18b20_init(bus, rom_code)) {
printf("Failed to initialize DS18B20 sensor
");
onewire_bus_deinit(bus);
return;
}

while (1) {
// Request temperature measurement
if (ds18b20_start_conversion(bus, rom_code)) {
// Wait for the conversion to complete
vTaskDelay(pdMS_TO_TICKS(750));

// Read the temperature
float temperature;
if (ds18b20_get_temperature(bus, rom_code, &temperature)) {
printf("Temperature: %.2f°C
", temperature);
} else {
printf("Failed to read temperature
");
}
} else {
printf("Failed to start temperature conversion
");
}

vTaskDelay(pdMS_TO_TICKS(2000)); // Delay 2 seconds
}

// Deinitialize the 1-Wire bus
onewire_bus_deinit(bus);
}

  • #include "onewire.h" and #include "ds18b20.h" import libraries for 1-Wire communication and sensor handling.
  • #define DS18B20_GPIO GPIO_NUM_4 specifies the GPIO pin connected to the sensor's data line.
  • In the app_main() function, the 1-Wire bus is initialized with onewire_bus_init().
  • The code searches for a DS18B20 device, initializes it, and continuously reads temperature values using ds18b20_get_temperature().
  • The temperature is printed to the serial monitor using printf().

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.

ESPHome Image

ESP32 DS18B20 ESPHome Code Example

Example in ESPHome (Home Assistant)

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

The code defines a JSON property sensor_config containing a stringified object. It includes a sensor array with attributes like platform (sensor type), address (hardware ID), name (sensor label), and update_interval (update frequency).

Upload this code to your ESP32 using the ESPHome dashboard or the esphome run command.

PlatformIO Image

ESP32 DS18B20 PlatformIO Code Example

Example in PlatformIO Framework

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 with sensors.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 using Serial.print().

Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload command.

MicroPython Image

ESP32 DS18B20 MicroPython Code Example

Example in Micro Python Framework

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, and import 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 and DS18X20 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, and ds.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.

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:

sensors.requestTemperatures(); float tempC = sensors.getTempCByIndex(0);

if (tempC == -127.0) { Serial.println("Error: Sensor communication failure. Retrying..."); delay(1000); // Retry delay sensors.requestTemperatures(); tempC = sensors.getTempCByIndex(0); }

if (tempC != -127.0) { Serial.print('Temperature: '); Serial.println(tempC); } else { Serial.println('Error persists. Check wiring or replace sensor.'); }

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.