Raspberry Pi DS18B20 Temperature Sensing

In this tutorial you will learn how to read temperature using DS18B20 temperature sensor and Raspberry Pi.

Update: If you are using the latest software for your Pi then you will need to edit the /boot/config.txt file and add the following lines to the bottom of the file, save and reboot:

# 1-wire settings
dtoverlay=w1-gpio

DS18B20 temperature sensor is a good choice for Raspberry Pi since Raspberry Pi lacks built in ADC (Analogue to Digital Converter) and so cannot read temperatures directly from analogue temperature sensors such as TMP36.

These temperature sensors are highly accurate and come in a small TO-92 package. Waterproof versions are also available.

Hardware

For this tutorial you will need Raspberry Pi, DS18B20 digital temperature sensor, 4.7K resistor, small breadboard and some jumper wires. Although not necessary a GPIO breakout kit is very helpful.

The DS18B20 sensors can be connected in parallel. All sensors should share the same pins, but only one 4.7K resistor is necessary for all of them. Resistor acts as a ‘pull-up’ for the data line to keep the signal stable.

The breadboard layout for a basic, single DS18B20 sensor circuit is shown below.

Note: be careful to connect the DS18B20 sensor the right way round. If you connect it the wrong way round it will get hot and break.

DS18B20 circuit

Software

To test that the sensor is wired up correctly and to play around with it we are going to enter some commands in the terminal.

Open new terminal window and enter following commands pressing Enter after each line.

sudo modprobe w1-gpio
sudo modprobe w1-therm
cd /sys/bus/w1/devices
ls

Once you are in the devices directory and list all the files you will see a directory starting with ’28-‘.
Change directory to whatever directory name you find there. If you have more than one sensor connected the devices directory will contain multiple 28-xxx directories. Each one is a unique identifier for each sensor attached to the Raspberry Pi.

[box type=”info”]Tip: if using multiple sensors, attach them to the network one by one checking the devices directory after each sensor is attached and label the sensors accordingly to their ID. This will help you identify which temperature reading belongs to which sensor.[/box]

Next enter

cd 28-xxxxxxxxxxxx (replace xxxx... withe the actual directory name)
cat w1_slave

The cat w1_slave command will display contents of the w1_slave file which contains the temperature readings.
The response will contain YES or NO at the end of the first line which indicates whether the temperature has been read successfully. If it is YES the temperature will be at the end of the second line in 1/1000 of degrees °C.

In our example below the temperature is 21.937 °C the first two times and 23.625 °C the third time (I’ve put my finger onto the sensor to make sure it is working).

DS18B20 terminal commands

[box type=”info”]To load the 1-wire kernel modules on every boot edit the /etc/modules file

sudo nano /etc/modules

and add w1-gpio and w1-therm to the end of the file and save.[/box]

Add 1-wire kernel modules to the modules file

Python code

Below is a python code that will read the temperature from all the sensors attached to the Raspberry Pi and print out the device name and current temperature reading in celsius.

import os, glob, sys
from time import sleep

# Load the 1-wire modules (if modules are loaded on boot these two lines can be commented out)
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

# Set up some variables
base_dir = '/sys/bus/w1/devices/'
devices = glob.glob(base_dir + '28*')
device_file = '/w1_slave'

def read_temp_file(device_file):
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_all():
    for  device in devices:
        device_dir = device + device_file
        raw_data = read_temp_file(device_dir)

        while raw_data[0].find('YES') == -1:
            sleep(0.1)
            raw_data = read_temp_file(device_dir)

        t_pos = raw_data[1].find('t=')

        if t_pos != -1:
            temp = float(raw_data[1][t_pos+2:]) / 1000
            print('%s - %.1f%s' % (device, temp, u"\u00b0"+'C'))

try:
    while True:
        read_all()
        sleep(1)
except KeyboardInterrupt:
    # quit
    print('Exiting application')
    sys.exit()

Below is the output from the python code with three sensors connected to the Raspberry Pi.

DS18B20 python code output

To test the python code upload it to your Raspberry Pi via SSH or SFTP as temperature.py file and run it by typing

sudo python temperature.py

Try and pinch the sensor with your fingers to warm it up and see if the temperature changes.