The Python program deals with any failed messages and reports the temperature in degrees C and F every second.

import glob
import time

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

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    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
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f

while True:
    print(read_temp())
    time.sleep(1)

The next three lines, find the file from which the messages can be read.

def read_temp_raw():
	catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	out,err = catdata.communicate()
	out_decode = out.decode('utf-8')
	lines = out_decode.split('\n')
	return lines

Reading the temperature takes place in two functions, read_temp_raw just fetches the two lines of the message from the interface. The read_temp function wraps this up checking for bad messages and retrying until it gets a message with 'YES' on end of the first line. The function returns two values, the first being the temperature in degrees C and the second in degree F.

You could if you wished separate these two as shown in the example below:

deg_c, deg_f = read_temp()

The main loop of the program simply loops, reading the temperature and printing it, before sleeping for a second.

To upload the program onto your Raspberry Pi, you can use SSH to connect to the Pi, start an editor window using the line:

nano thermometer.py

and then paste the code above, before saving the file with CTRL-x and Y.

This guide was first published on Jan 28, 2013. It was last updated on Jan 28, 2013.

This page (Software) was last updated on Jun 20, 2021.

Text editor powered by tinymce.