SunFounder DS18B20 Temperature Module for Raspberry Pi – Part 2

Here is some python code from the SunFounder site that is part of their sensor kit install.

Let’s get back to our Raspberry home directory if you are not already. You can technically out the python script anyplace you like but I prefer the pi user home directory. Type the following if needed in Terminal.

cd /home/pi/

Now let’s create a python script. Copy the following code below then type the following again in Terminal.

sudo nano getTemp.py

Past the text below into the file.  This will get the temp from the sensors that start with “28”

#!/usr/bin/env python
import os
import time

#---------------------------------------------------
#	Note:
#		ds18b20's data pin must be connected to pin7.
#---------------------------------------------------

# Reads temperature from sensor and prints to stdout
# id is the id of the sensor
def readSensor(id):
	tfile = open("/sys/bus/w1/devices/"+id+"/w1_slave")
	text = tfile.read()
	tfile.close()
	secondline = text.split("\n")[1]
	temperaturedata = secondline.split(" ")[9]
	temperature = float(temperaturedata[2:])
	temperature = temperature / 1000
	print "Sensor: " + id  + " - Current temperature : %0.3f C" % temperature


# Reads temperature from all sensors found in /sys/bus/w1/devices/
# starting with "28-...
def readSensors():
	count = 0
	sensor = ""
	for file in os.listdir("/sys/bus/w1/devices/"):
		if (file.startswith("28-")):
			readSensor(file)
			count+=1
	if (count == 0):
		print "No sensor found! Check connection"

# read temperature every second for all connected sensors
def loop():
	while True:
		readSensors()
		time.sleep(1)

# Nothing to cleanup
def destroy():
	pass

# Main starts here
if __name__ == "__main__":
	try:
		loop()
	except KeyboardInterrupt:
		destroy()

 

ds18b20 = '28-051684d013ff'

Now we can save and exit the nano editor.  Ctrl+o to save the file and Ctrl+x to exit.

Now we can run the python script to see the results.

python getTemp.py 

You should see something like the following start to display.

Sensor: 28-051684d013ff - Current temperature : 21.437 C
Sensor: 28-051684d013ff - Current temperature : 21.500 C
Sensor: 28-051684d013ff - Current temperature : 21.500 C
Sensor: 28-051684d013ff - Current temperature : 21.500 C
Sensor: 28-051684d013ff - Current temperature : 21.500 C
Sensor: 28-051684d013ff - Current temperature : 21.500 C

You can stop the script from running with a Ctrl+z.

In part 3 of this tutorial I will show you how to get the temp sensor results showing up in Homebridge for your home automation.

Leave a Reply

Your email address will not be published. Required fields are marked *