The DS18B20 is a digital temperature sensor that provides highly accurate temperature readings over a range of -55°C to +125°C. Unlike analog sensors, it communicates over the OneWire protocol, which means multiple DS18B20 sensors can be connected to a single pin of the ESP32.
Key features include:
In this tutorial, we will:
DS18B20 Pin | ESP32 DOIT Kit Pin |
---|---|
VCC | 3.3V |
GND | GND |
DATA | GPIO 26 |
⚡ Important: Connect a 4.7kΩ resistor between DATA and VCC (pull-up resistor).
Before coding, install the following libraries in Arduino IDE:
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to GPIO 26
#define ONE_WIRE_BUS 26
// Setup a oneWire instance
OneWire oneWire(ONE_WIRE_BUS);
// Pass oneWire reference to Dallas Temperature
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(115200);
sensors.begin(); // Start DS18B20 sensor
}
void loop() {
sensors.requestTemperatures(); // Send command to get temperature
float temperatureC = sensors.getTempCByIndex(0); // Read temperature in °C
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
delay(1000); // Wait 1 second
}
Include Libraries
#include <OneWire.h>
#include <DallasTemperature.h>
Adds support for OneWire and DS18B20 communication.
Define Pin
#define ONE_WIRE_BUS 26
Data pin of DS18B20 connected to GPIO 26.
Initialize OneWire & DallasTemperature
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
Creates communication objects.
Setup Function
sensors.begin();
Starts sensor communication.
Loop Function
sensors.requestTemperatures();
float temperatureC = sensors.getTempCByIndex(0);
Requests and reads temperature (sensor at index 0 if only one connected).
Print Output
Serial.println("Temperature: ... °C");
Displays temperature on Serial Monitor.
getDeviceCount()
and unique addresses.The DS18B20 works between 3.0V to 5.5V, so it’s safe to use with the ESP32’s 3.3V supply.
The DS18B20 uses the OneWire protocol, and a pull-up resistor ensures stable data communication between the sensor and ESP32.
This usually indicates the sensor is not detected. Check wiring, pull-up resistor, and ensure the correct GPIO pin is used.
Yes ✅, the DS18B20 supports multiple sensors on a single pin since each sensor has a unique 64-bit address.
It has a typical accuracy of ±0.5°C in the range of -10°C to +85°C.
DS18B20 → Only measures temperature (digital, high accuracy).
DHT22 → Measures both temperature and humidity (slightly less accurate for temperature).
Yes, the waterproof version of the DS18B20 is designed for outdoor and liquid applications like aquariums, water tanks, and soil monitoring.
This is the default reading if the ESP32 fails to properly initialize the DS18B20. Try restarting or checking the wiring.