Interfacing DS18B20 Temperature Sensor with ESP8266 NodeMCU
Learn how to connect a DS18B20 1-Wire digital temperature sensor to an ESP8266 (NodeMCU) board and read temperature values via the Serial Monitor in Celsius.
1. Overview & Specifications
The DS18B20 is a 1-Wire digital temperature sensor that measures temperatures from -55°C to +125°C with ¹0.5°C accuracy (between -10°C and +85°C). It operates on a supply voltage from 3.0V to 5.5V, making it fully compatible with the 3.3V logic level of the ESP8266.
2. Bill of Materials (BOM)
- 1x ESP8266 Development Board (NodeMCU)
- 1x DS18B20 Temperature Sensor (TO-92 or Waterproof Probe)
- 1x 4.7 kΊ Resistor (1/4W)
- 1x Breadboard & Jumper Wires
3. Hardware Connections & Pinout
The DS18B20 uses a single data line for communication (1-Wire protocol). A 4.7 kΊ pull-up resistor is required between the DQ (Data) line and the 3.3V supply line for stable communication.
DS18B20 Pinout Table
| DS18B20 Pin | Function | ESP8266 Connection |
|---|---|---|
| Pin 1 (GND) | Ground | GND |
| Pin 2 (DQ) | 1-Wire Data Line | D4 (GPIO2) (Requires 4.7 kΊ pull-up to 3.3V) |
| Pin 3 (VDD) | Power Supply (3.0V â 5.5V) | 3.3V |
4. Required Arduino Libraries
Before uploading the code, install the following libraries via the Arduino IDE Library Manager (Tools > Manage Libraries):
- OneWire by Paul Stoffregen
- DallasTemperature by Miles Burton
5. Source Code
Upload the following low-level ANSI-compatible C++ Arduino sketch to your NodeMCU board:
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to NodeMCU Pin D4 (GPIO2)
#define ONE_WIRE_BUS D4
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor handler
DallasTemperature sensors(&oneWire);
void setup() {
// Initialize serial communication at 115200 baud
Serial.begin(115200);
// Start up the DallasTemperature library
sensors.begin();
}
void loop() {
// Send the command to request temperature from all devices on the bus
sensors.requestTemperatures();
// Fetch temperature in Celsius for the first sensor on the bus (index 0)
float tempC = sensors.getTempCByIndex(0);
// Output result to Serial Monitor
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println(" °C");
// Delay 1 second before the next reading
delay(1000);
}
6. Testing & Verification
- Connect your NodeMCU board to your PC via Micro-USB.
- Select board NodeMCU 1.0 (ESP-12E Module) and correct COM port in Arduino IDE.
- Compile and upload the sketch.
- Open the Serial Monitor set to 115200 baud.
- You should see real-time temperature updates printed every second.