0
0
Iot-protocolsHow-ToBeginner · 4 min read

Raspberry Pi Temperature Monitor Project: Simple Guide

Use a DS18B20 temperature sensor connected to your Raspberry Pi's GPIO pins and write a Python script to read and display temperature data. This project involves enabling the sensor interface, reading sensor data from the system files, and printing the temperature in Celsius.
📐

Syntax

To read temperature from a DS18B20 sensor on Raspberry Pi, you use Python to access system files created by the sensor driver. The main steps are:

  • Enable 1-Wire interface on Raspberry Pi.
  • Locate the sensor device folder in /sys/bus/w1/devices/.
  • Read the temperature data from the w1_slave file.
  • Parse the raw data to get the temperature in Celsius.
python
import os
import glob
import time

def read_temp_raw():
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[0]
    device_file = device_folder + '/w1_slave'
    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
💻

Example

This example reads the temperature from the DS18B20 sensor every second and prints it to the screen in Celsius.

python
import os
import glob
import time

def read_temp_raw():
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[0]
    device_file = device_folder + '/w1_slave'
    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

if __name__ == '__main__':
    try:
        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)
    except KeyboardInterrupt:
        print("Temperature monitoring stopped.")
Output
Current Temperature: 23.75 °C Current Temperature: 23.81 °C Current Temperature: 23.78 °C ... (updates every second)
⚠️

Common Pitfalls

Common mistakes when building a Raspberry Pi temperature monitor include:

  • Not enabling the 1-Wire interface in Raspberry Pi settings, so the sensor is not detected.
  • Using the wrong GPIO pin or wiring the sensor incorrectly.
  • Trying to read the sensor before the device folder appears in /sys/bus/w1/devices/.
  • Not checking if the sensor data is valid before parsing.

Always verify wiring and enable 1-Wire via sudo raspi-config under Interface Options.

python
## Wrong way: Not checking for sensor folder
import glob

base_dir = '/sys/bus/w1/devices/'
# This may fail if no sensor is connected or enabled
sensor_folders = glob.glob(base_dir + '28*')
if sensor_folders:
    device_folder = sensor_folders[0]
else:
    print('Sensor not found. Check wiring and 1-Wire settings.')
Output
Sensor not found. Check wiring and 1-Wire settings.
📊

Quick Reference

Tips for a successful Raspberry Pi temperature monitor project:

  • Enable 1-Wire interface using sudo raspi-config.
  • Connect DS18B20 sensor data pin to GPIO4 (pin 7) with a 4.7kΩ pull-up resistor to 3.3V.
  • Use Python to read sensor data from /sys/bus/w1/devices/28-xxxx/w1_slave.
  • Parse the temperature value after t= in the sensor output.
  • Handle errors and sensor absence gracefully in code.

Key Takeaways

Enable the 1-Wire interface on Raspberry Pi before connecting the DS18B20 sensor.
Read temperature data by accessing the sensor's system file and parsing the output.
Check for sensor presence and valid data to avoid runtime errors.
Use a pull-up resistor on the sensor data line for reliable readings.
Test wiring carefully and handle exceptions in your Python code.