0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use DS18B20 Temperature Sensor with Raspberry Pi

To use the DS18B20 temperature sensor with a Raspberry Pi, connect it to the GPIO pins with a 4.7kΩ pull-up resistor on the data line, enable the 1-Wire interface, and read temperature data from the device file in /sys/bus/w1/devices/. You can also use Python to read and convert the sensor data easily.
📐

Syntax

The DS18B20 sensor uses the 1-Wire protocol. On Raspberry Pi, you enable the 1-Wire interface and read temperature data from a special file path.

  • /sys/bus/w1/devices/: Directory where sensor data appears.
  • 28-xxxxxxx: Folder named after the sensor's unique ID.
  • w1_slave: File containing raw temperature data.

Python code reads this file, extracts the temperature, and converts it to Celsius.

python
import os
import glob
import time

# Load 1-Wire drivers
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

# Base directory for 1-Wire devices
base_dir = '/sys/bus/w1/devices/'

# Find device folder starting with '28' (DS18B20 sensors)
device_folder = glob.glob(base_dir + '28*')[0]

# Path to sensor data file
device_file = device_folder + '/w1_slave'

# Function to read raw data
def read_temp_raw():
    with open(device_file, 'r') as f:
        lines = f.readlines()
    return lines

# Function to parse temperature
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c
    return None
💻

Example

This example shows how to read the temperature from the DS18B20 sensor and print it every second.

python
import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    with open(device_file, 'r') as f:
        lines = f.readlines()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c
    return None

while True:
    temperature = read_temp()
    if temperature is not None:
        print(f"Current Temperature: {temperature:.2f} °C")
    else:
        print("Failed to read temperature")
    time.sleep(1)
Output
Current Temperature: 23.75 °C Current Temperature: 23.75 °C Current Temperature: 23.75 °C
⚠️

Common Pitfalls

  • Not enabling 1-Wire interface: You must enable it via raspi-config or by adding dtoverlay=w1-gpio to /boot/config.txt.
  • Missing pull-up resistor: The data line needs a 4.7kΩ resistor between data and 3.3V for proper communication.
  • Wrong wiring: Connect sensor GND to Pi GND, VDD to 3.3V, and data to GPIO4 (pin 7) by default.
  • Reading data too fast: The sensor needs time to update; add delays between reads.
none
## Wrong wiring example (no pull-up resistor):
# Data line connected directly without resistor

## Correct wiring snippet:
# Connect 4.7kΩ resistor between data line and 3.3V
# Data line -> GPIO4 (pin 7)
# VDD -> 3.3V
# GND -> Ground
📊

Quick Reference

StepDescription
1Connect DS18B20 sensor with 4.7kΩ pull-up resistor to GPIO4 (pin 7)
2Enable 1-Wire interface via raspi-config or /boot/config.txt
3Load kernel modules: w1-gpio and w1-therm
4Find sensor folder in /sys/bus/w1/devices/ starting with '28'
5Read temperature from w1_slave file and parse it
6Use Python script to automate reading and display temperature

Key Takeaways

Enable the 1-Wire interface on Raspberry Pi before using DS18B20.
Use a 4.7kΩ pull-up resistor on the data line for reliable sensor communication.
Read temperature data from the device file in /sys/bus/w1/devices/28-xxxx/w1_slave.
Use Python to parse and convert raw sensor data to Celsius easily.
Add delays between reads to allow the sensor to update temperature values.