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:
- Raspberry Pi (Any model with GPIO pins, running Raspberry Pi OS)
- DS18B20 Temperature Sensor ( Waterproof probe or TO-92 transistor style)
- 4.7k Ohm Resistor (Used as a pull-up resistor between data and power)
- Breadboard and Jumper Wires (For making temporary, solderless connections)
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:
- Connect the GND pin of the sensor to Pin 6 (GND) on the Raspberry Pi.
- Connect the VCC pin of the sensor to Pin 1 (3.3V) on the Raspberry Pi.
- Connect the DQ (Data) pin of the sensor to Pin 7 (GPIO 4) on the Raspberry Pi.
- Place a 4.7k Ohm resistor between the VCC pin and the DQ pin. This pull-up resistor is crucial for stabilizing the data signal.
Enabling the 1-Wire Interface
Before the Raspberry Pi can recognize the sensor, you must enable the 1-Wire interface in the system configuration.
- Open the terminal on your Raspberry Pi or connect via SSH.
- Run the command
sudo raspi-configto open the configuration tool. - Navigate to Interface Options using the arrow keys.
- Select 1-Wire and choose Yes to enable it.
- 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/
lsYou 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_slaveThe 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.