Connecting and Reading a Raspberry Pi Temperature Sensor

This guide provides a straightforward walkthrough for connecting a DS18B20 digital temperature sensor to a Raspberry Pi and reading its data using Python. You will learn about the necessary hardware components, how to wire the sensor to the Pi’s GPIO pins, and the configuration steps required to enable the 1-Wire interface. Finally, we will write a simple Python script to parse and display real-time temperature readings.

Required Hardware Components

To get started, you will need a few basic electronic components:

Wiring the DS18B20 to the Raspberry Pi

The DS18B20 sensor operates using the 1-Wire protocol, meaning it requires only one data pin to communicate with the Raspberry Pi. The sensor has three pins: VCC (Power), GND (Ground), and DQ (Data).

The wiring connections are as follows:

Enabling the 1-Wire Interface

Before the Raspberry Pi can recognize the sensor, you must enable the 1-Wire interface in the system configuration.

  1. Open the terminal on your Raspberry Pi or connect via SSH.
  2. Run the command sudo raspi-config to open the configuration tool.
  3. Navigate to Interface Options using the arrow keys.
  4. Select 1-Wire and choose Yes to enable it.
  5. Finish and reboot your Raspberry Pi to apply the changes.

Alternatively, you can enable it by adding dtoverlay=w1-gpio to the end of the /boot/config.txt file and rebooting.

Verifying the Sensor Connection

Once the Pi reboots, you can check if the system detects the sensor by looking into the 1-Wire directory. Run the following commands in the terminal:

cd /sys/bus/w1/devices/
ls

You should see a directory name starting with 28-, such as 28-00000xxxxxxx. This unique serial number belongs to your DS18B20 sensor. To see the raw data output, enter the sensor directory and read the w1_slave file:

cd 28-00000xxxxxxx
cat w1_slave

The output will contain two lines of text, with the end of the second line showing t=XXXXX, where the number represents the temperature in degrees Celsius multiplied by 1000.

Writing the Python Script to Read Data

To automate this process and convert the raw data into readable Celsius and Fahrenheit temperatures, you can use a Python script. Create a new file named temperature.py and insert the following code:

import os
import time
import glob

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

# Find the correct device file path
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:
        return f.readlines()

def read_temp():
    lines = read_temp_raw()
    # Wait until the sensor response is valid
    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
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f

try:
    while True:
        temp_c, temp_f = read_temp()
        print(f"Temperature: {temp_c:.2f}°C | {temp_f:.2f}°F")
        time.sleep(1)
except KeyboardInterrupt:
    print("\nProgram stopped by user.")

Run the script by typing python3 temperature.py in your terminal. The script will output the current temperature every second until you press Ctrl+C to stop it.