Adafruit will not be shipping orders Monday May 30, 2016 for the federal holiday, Memorial Day. Orders placed after 11 AM EST Friday May 27 will go out Tuesday May 31.

Software

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

import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

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 program starts by issuing the 'modprobe' commands that are needed to start the interface running.

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

A problem has been reported with occasional hangs when reading the temperature file when using Raspbian. If you find you have the same problem, try replacing the function read_temp_raw with the code below. You will also need to add a line at the top of the file 'import subprocess'.

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.

Last updated on 2015-05-04 at 04.27.11 PM Published on 2013-01-28 at 04.35.41 PM