Magicshine
Posts: 1
Joined: Sat Dec 12, 2015 12:08 am

Reading multiple DS18B20 with Python

Sat Dec 12, 2015 10:27 am

Hi All,

I'm somewhat experienced with Pi, but python not so.

I have a project on the go at the moment to read the output from multiple (currently 2, need up to 5 or 6) DS18B20 sensors.
The below script I have (sourced online) will read two devices, strip the output down and show a prefix (T:) with the temp.
I have tried and tried and tried to modify the script to add 4 sensors but I get various different errors based on how I try to modify it.

Could someone have a look over it and see if theres a way to do this?

Code: Select all

#!/usr/bin/python
# This file is: /usr/share/cacti/site/scripts/flow_temps.py

import os, glob, time, sys, datetime

#Set up the location of the DS18B20 sensors in the system
device_folder = glob.glob('/sys/bus/w1/devices/28*')
device_file = [device_folder[0] + '/w1_slave',device_folder[1] + '/w1_slave']

def read_temp_raw(): #A function that grabs the raw temp data from the sensors
	f_1 = open(device_file[0], 'r')
	lines_1 = f_1.readlines()
	f_1.close()
	f_2 = open(device_file[1], 'r')
	lines_2 = f_2.readlines()
	f_2.close()
	return lines_1 + lines_2

def read_temp(): #A function to check the connection was good and strip out the temperature
	lines = read_temp_raw()
	while lines[0].strip()[-3:] != 'YES' or lines[2].strip()[-3:] != 'YES':
		time.sleep(0.2)
		lines = read_temp_raw()
	equals_pos = lines[1].find('t='), lines[3].find('t=')
	temp = float(lines[1][equals_pos[0]+2:])/1000, float(lines[3][equals_pos[1]+2:])/1000
	return temp

temp = read_temp() #get the temp
print('T1:'+str(temp[0])+' T2:'+str(temp[1]))
I am using Cacti to graph the output, which is working well and this script is run by a cron job. I am just stuck reading from more than 2 devices but again I dont know much Python!

Thanks in advance

User avatar
RogerW
Posts: 269
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: Reading multiple DS18B20 with Python

Sun Dec 13, 2015 2:32 pm

You could try this code. The first file contains a class definition for a DS18B20 object.

Code: Select all

# ds18b20.py
# written by Roger Woollett

import os
import glob
import time

class DS18B20:
	# much of this code is lifted from Adafruit web site
	# This class can be used to access one or more DS18B20 temperature sensors
	# It uses OS supplied drivers and one wire support must be enabled
	# To do this add the line
	# dtoverlay=w1-gpio
	# to the end of /boot/config.txt
	#
	# The DS18B20 has three pins, looking at the flat side with the pins pointing
	# down pin 1 is on the left
	# connect pin 1 to GPIO ground
	# connect pin 2 to GPIO 4 *and* GPIO 3.3V via a 4k8 (4800 ohm) pullup resistor
	# connect pin 3 to GPIO 3.3V
	# You can connect more than one sensor to the same set of pins
	# Only one pullup resistor is required
	
	def __init__(self):
		# load required kernel modules
		os.system('modprobe w1-gpio')
		os.system('modprobe w1-therm')
		
		# Find file names for the sensor(s)
		base_dir = '/sys/bus/w1/devices/'
		device_folder = glob.glob(base_dir + '28*')
		self._num_devices = len(device_folder)
		self._device_file = list()
		i = 0
		while i < self._num_devices:
			self._device_file.append(device_folder[i] + '/w1_slave')
			i += 1
		
	def _read_temp(self,index):
		# Issue one read to one sensor
		# you should not call this directly
		f = open(self._device_file[index],'r')
		lines = f.readlines()
		f.close()
		return lines
		
	def tempC(self,index = 0):
		# call this to get the temperature in degrees C
		# detected by a sensor
		lines = self._read_temp(index)
		retries = 5
		while (lines[0].strip()[-3:] != 'YES') and (retries > 0):
			# read failed so try again
			time.sleep(0.1)
			#print('Read Failed', retries)
			lines = self._read_temp(index)
			retries -= 1
			
		if retries == 0:
			return 998
			
		equals_pos = lines[1].find('t=')
		if equals_pos != -1:
			temp = lines[1][equals_pos + 2:]			
			return float(temp)/1000
		else:
			# error
			return 999
			
	def device_count(self):
		# call this to see how many sensors have been detected
		return self._num_devices
The second file is a test program, put it in the same directory.

Code: Select all

# Temp.py

from ds18b20 import DS18B20	
	
# test temperature sensors
x = DS18B20()
count=x.device_count()
i = 0
while i < count:
	print(x.tempC(i))
	i += 1
This should show the output from multiple sensors.

sroof
Posts: 12
Joined: Sun Jan 12, 2014 2:10 am

Re: Reading multiple DS18B20 with Python

Fri Oct 14, 2016 7:45 pm

RogerW - Thanks for code for reading multiple ds18B20 sensors. Your code is a little beyond my Python comprehension but works for me. However, I need to know which sensor is sending which temperature. Can you suggest a way to print out sensor serial numbers along with each temperature reading?
Thanks!

User avatar
joan
Posts: 13556
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Reading multiple DS18B20 with Python

Fri Oct 14, 2016 7:48 pm

Another variation.

Code: Select all

#!/usr/bin/env python

import glob
import time

# DS18B20.py
# 2016-04-25
# Public Domain

# Typical reading
# 73 01 4b 46 7f ff 0d 10 41 : crc=41 YES
# 73 01 4b 46 7f ff 0d 10 41 t=23187

while True:

   for sensor in glob.glob("/sys/bus/w1/devices/28-00*/w1_slave"):
      id = sensor.split("/")[5]

      try:
         f = open(sensor, "r")
         data = f.read()
         f.close()
         if "YES" in data:
            (discard, sep, reading) = data.partition(' t=')
            t = float(reading) / 1000.0
            print("{} {:.1f}".format(id, t))
         else:
            print("999.9")

      except:
         pass

   time.sleep(3.0)

Devilx
Posts: 3
Joined: Fri Oct 28, 2016 8:38 pm

Re: Reading multiple DS18B20 with Python

Fri Oct 28, 2016 8:47 pm

Hey! Joan the coding given by you prints the temp from one temperature sensor only.
Can anyone help me getting a code that reads multiple temperature sensor( likely to be 8) with distinct differentiation from which sensor it was taken using pi and with every temperature( in deg C) recorded it has date, time record as well? I am beginner in python, so it's obvious that I can write such complex programs and have to complete biology project soon ..

Help me please

sroof
Posts: 12
Joined: Sun Jan 12, 2014 2:10 am

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 2:19 am

Devilx - I found Joan's code brilliant and efficient but it may only work with the newer Raspian Jesse. And it DOES require having the line dtoverlay=w1-gpio at the end of /boot/config.txt. The code automatically recognize any and all 1-wire sensors properly connected to the Pi and drops any sensor that is disconnected. That is, sensor folders such as 28-000004cb051b in /sys/bus/w1/devices appear and disappear automatically. If you're not getting results, check to see that you've got your 1-wire sensors wired up properly.
I added a couple of lines that accumulates the serial number of each sensor along with the temperature value into a string called "datastring". This code works for me with 6 1-wire sensors:

Code: Select all

datastring = ''
for sensor in glob.glob("/sys/bus/w1/devices/28-00*/w1_slave"):
    id = sensor.split("/")[5]
    try:
        f = open(sensor, "r")
      	data = f.read()
      	f.close()
      	if "YES" in data:
            (discard, sep, reading) = data.partition(' t=')
            t = float(reading) / 1000.0    #reports temperature in degrees C
            datastring = datastring + id + ':' + str(t) + ','
    
    except:    
        pass

Devilx
Posts: 3
Joined: Fri Oct 28, 2016 8:38 pm

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 11:20 am

Thank you very much Sroof !!

Can you help me again? I need to read temperature from 8+ sensors and log that data in .txt file ( with date , time and sensor id as well). I tried it but couldn't fix it.

Thank you again.

sroof
Posts: 12
Joined: Sun Jan 12, 2014 2:10 am

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 12:49 pm

Devilx – First check that your sensors are wired up correctly to your Pi. If everything is working, you should see a series of folders in /sys/bus/w1/devices with names like “28-000004cb051b”. There should be one folder for each 1-wire sensor. If you’re not seeing sensor folders, then re-read the instructions from Adafruit: https://learn.adafruit.com/adafruits-ra ... g?view=all

If you are seeing all your 1-wire folders, then what output are you seeing from the above code?

danjperron
Posts: 3023
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 2:12 pm

I always create a config file with the ID of each sensors. This way when I collect the data I'm always sure that the system will read all of them and I will get the right sequence order if one sensor is not detected.

This is a most unless you are using a dictionary to capture the temperature with the corresponding ID.

I create my config file with this command

Code: Select all

cd
ls -1 /sys/bus/w1/devices/ | grep "28" >DS18B20.conf
After that check the file using

Code: Select all

nano DS18B20.conf
You should have all your sensors.
Also add a label at the end of the line. You just need the let a space after the ID.

This is what my DS18B20.conf looks like
[email protected]:~ $ cat DS18B20.conf
28-000006f058c9 sensor1
28-0215c26f41ff sensor2
28-800000015bfa sensor3


This is a small python script to read the DS18B20.conf and record the data to a file "temperature.txt"
I modified my script and get rid of the HTML and RRDTOOL function just to simplify it.

Code: Select all

[email protected]:~ $ ./ReadDS18B20.py 
ID= 28-000006f058c9  Temp= 18.8  LABEL=sensor1
ID= 28-0215c26f41ff  Temp= 18.9  LABEL=sensor2
ID= 28-800000015bfa  Temp= 18.6  LABEL=sensor3
[email protected]:~ $
And this is the output of temperature.txt

Code: Select all

[email protected]:~ $ cat temperature.txt 
10/29/16 09:47:34	38.5	18.7	18.7	18.5
10/29/16 09:47:38	39.0	18.7	18.7	18.5
10/29/16 09:58:48	38.5	18.8	18.7	18.5
10/29/16 10:00:00	38.5	18.8	18.9	18.6
In the file you have the date,time, cpu temperature and the DS18B20. I do have 3 sensors connected.

you could get my file from dropbox

Code: Select all

wget https://dl.dropboxusercontent.com/u/48891705/rpi/DS18B20/ReadDS18B20.py
Since Jessie takes care of 1 wire modules there is no needs to add the insmod lines. If you aren't on Jessie yet please upgrade it and enable the 1 wire using the GUI interface or raspi-config.

User avatar
bensimmo
Posts: 3190
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 2:26 pm

You may also want to have a look at Timo's W1thermsensor https://timofurrer.github.io/w1thermsensor/ as well.

Devilx
Posts: 3
Joined: Fri Oct 28, 2016 8:38 pm

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 9:46 pm

sroof !! I did and went to adafruit and i got everything as said there. BUt now, i need to add 8 more temperature sensors, read temprature and write that to a text file with date and time and sensor id as well.

danjperron
Posts: 3023
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Reading multiple DS18B20 with Python

Sat Oct 29, 2016 11:16 pm

Code: Select all

I did and went to adafruit and i got everything as said there. BUt now, i need to add 8 more temperature sensors, read temprature and write that to a text file with date and time and sensor id as well.
So what about my script which does that ?

PeteCress
Posts: 59
Joined: Sat Oct 29, 2016 1:11 pm

Re: Reading multiple DS18B20 with Python

Tue Nov 15, 2016 6:28 pm

For better or worse, here's something that is working right now under Python 2.7.9 and which monitors 2 sensors using Timo's W1ThermSensor library.

One sensor measures temperature within a backup file server's case and the other measures the temperature within the garden shed that the server lives in.

It should scale to using more sensors by discovering/adding the sensorIDs of the additional sensors and amending the code to do with them whatever is desired.

It writes two text logs: one cumulative and another that covers the current 24-hour period.

It also displays some data on the Command line - mainly for testing/feelgood:

Code: Select all

# --------------------------------------------------------
# PURPOSE: - To monitor temperatures within a backup server's 
#            case and within the garden shed it is running in
#          - To turn on heating or cooling if temperature within
#            server case gets out of a predetermined range    
#          - To log temperatures/times in a tab-delimited file
#            on a NAS box. 

import os
import glob
import time
import datetime
import RPi.GPIO as iO
import os,subprocess
from subprocess import call
from w1thermsensor import W1ThermSensor

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

# ======================================================================
# Define our subroutines:
# --------------------------------------------------
# Define a function to convert Celsius to Fahrenheit 

def celsiusToFahrenheit(theTempCelsius):
 myTempFarenheit = ((theTempCelsius*9)/5) + 32
 return myTempFarenheit
 
# --------------------------------------------------
# Define a function to get current temperature of the
# Raspberry Pi's CPU  (which, just for grins, we also
# want to monitor)

def getPiCPUtemperature():  
 res = os.popen('vcgencmd measure_temp').readline()  
 return(res.replace("temp=","").replace("'C\n",""))  
 
# --------------------------------------------------
# Define a function fo mount the NAS directory as 
# part of the Pi's file system

# NB: For reasons not yet discovered, using the NAS
#     box's name is not working, so we revert to 
#     it's numeric IP address.
#
#     //Giga2/D  works, no problem, but
#     //NAS/A    fails..... go figure....

def mountNasDirectory():
 myUNC="//10.0.0.8/A"
	
 myCmd = "sudo umount " + myLocalMountDir
 subprocess.Popen(myCmd, shell=True)
 
 myCmd = "sudo mount -t cifs " + myUNC + " " +  myLocalMountDir + " -o  uid=pi,gid=pi,user=admin,pass=xxx"
 subprocess.Popen(myCmd, shell=True)


# ======================================================================
# Perform startup processing: 

# -------------------------------------
# Specify the desired temprature range 
# and time between readings

caseTempDesiredC = int(25)
maxDeviation_BeforeCool = 1.5 
maxDeviation_BeforeHeat = 1.5 
secondsBetweenReadings = 60

# -------------------------------------
# Capture the date we started this script

myDateStamp_Startup =datetime.datetime.now().strftime("%Y-%m-%d")
myDateStamp_Today = myDateStamp_Startup

# -------------------------------------
# Specify NAS box directory in the Pi's
# file system's scheme of things
#
# NB: You might have to read up on this: somehow
#     this directory contains some sort of secret
#     sauce that allows the Pi's OS to populate it
#     with shortcuts to the actual NAS box's 
#     folders... possibly specified in the Samba
#     setup files.

myLocalMountDir="/mnt/NAS_A"
 
# -------------------------------------
# Refer to pins by Broadcom SOC channel
# instead of physical pin#

iO.setmode(iO.BCM)

# -------------------------------------
# Specify which pins are used to flip
# which relay switch on/off and then
# define them as "Output"

relayCool = 10
relayHeat = 11
iO.setwarnings(False)
iO.setup(relayCool, iO.OUT)
iO.setup(relayHeat, iO.OUT)

# -------------------------------------
# Turn off both relay switches - for 
# convenience in testing

iO.output(relayHeat, False)
iO.output(relayCool, False)

# -------------------------------------
# Specify the 3 possible heating/cooling states

tempStateNone = 0
tempStateCool = 1
tempStateHeat = 2 

# -------------------------------------
# Set a pointer to our W1Thermsensor object,
# which will give us easy access to the sensors

mySensor = W1ThermSensor()

# -------------------------------------
# Define sensors by ID (we had to experimentally
# discover these by writing a little script that
# opened the W1ThermSensor class, looped through
# the sensors it knew about and displayed "sensorID"
# for each sensor

sensorID_Case = "0000080222f8"
sensorID_Shed = "04165661cdff"

# -------------------------------------
# Mount the share on the NAS box that we
# will be writing the 2 logs to

mountNasDirectory()

# -------------------------------------
# Open the two tab-delimited log files on the
# NAS box: one for each 24-hour period the
# other cumulative since the last startup.
#
# NB: If either file already exists, we want to
#     open it for Append instead of new albeit 
#     with a blank line to call attention to the
#     fact that log entries were interrupted.
#
# NB: We have sometimes been having trouble with 
#     opening a new file failing w/ErrorCode=2 
#     even so the path is good - only to have
#     it work upon re-starting the script.  This
#     happens if/when somebody on another PC deleted
#     one or both log files while the script is running.

myLogFileDelim = "\t"

myFileHeader1 = myLogFileDelim.join(["\n" + "Temp Desired=" + str(caseTempDesiredC), "maxDeviation Before Cool=" + str(maxDeviation_BeforeCool), "maxDeviation Before Heat=" + str(maxDeviation_BeforeHeat)])
myFileHeader2 = myLogFileDelim.join(["\n" + "TimeStamp", "Case TempC ", "Heat/Cool State", "Shed TempC", "Shed TempF", "Pi CPU TempC"])
#myFileHeader2 = myLogFileDelim.join(["\n" + "TimeStamp", "Case TempC ", "Shed TempC", "Shed TempF", "Pi CPU TempC", "Heat/Cool State  (" + str(tempStateNone) +"=Nothing, " + str(tempStateCool) + "=Cool, " + str(tempStateHeat) + "=Heat)"])

myInterruptIndicator = myLogFileDelim.join(["\n" + "-"*45, "-"*45, "-"*45, "-"*45, "-"*45, "-"*45, "-"*45])

myLogFileSingleDay_Path = myLocalMountDir + "/Mongo_TemperatureLogs/MongoTempLog_SingleDay." + myDateStamp_Today + ".csv"
if os.path.exists(myLogFileSingleDay_Path):
	print("SingleDay: Append to Existing")
	logFileSingleDay = open(myLogFileSingleDay_Path, "a")
	logFileSingleDay.write(myInterruptIndicator)
	logFileSingleDay.write(myFileHeader1)
	logFileSingleDay.write(myFileHeader2)
		
else:	
	print("SingleDay: Create New")
	logFileSingleDay = open(myLogFileSingleDay_Path, "a")
	logFileSingleDay.write(myFileHeader1)
	logFileSingleDay.write(myFileHeader2)


myLogFileCumulative_Path = myLocalMountDir + "/Mongo_TemperatureLogs/MongoTempLog_Cumulative.csv"	
if os.path.exists(myLogFileCumulative_Path):
	print("Cumulative: Append to Existing")
	logFileCumulative = open(myLogFileCumulative_Path, "a")
	logFileCumulative.write(myInterruptIndicator)
	logFileCumulative.write(myFileHeader1)
	logFileCumulative.write(myFileHeader2)
else:	
	print("Cumulative: Create New")
	logFileCumulative = open(myLogFileCumulative_Path, "a")
	logFileCumulative.write(myFileHeader1)
	logFileCumulative.write(myFileHeader2)	
	
# ======================================================================
# Drop into the script's main loop, which keeps on executing until the
# script abends or is cancelled:
#
#    - Reading temp, 
#    - Checking to see if we need heating or cooling, and
#    - Writing temps to the log file

while True:
#   --------------------------------------------
#   See if we need to start a new 24-hour log
#
#   NB: re/"a" vs "w".... Greater Minds have decreed
#       there is no sense in using "w"... because
#       with "a" if the file does not exist, it 
#       gets created same as if we used "w".

	myDateStamp_Current  = datetime.datetime.now().strftime("%Y-%m-%d")
	
	if (myDateStamp_Current != myDateStamp_Today):
		myDateStamp_Today = myDateStamp_Current
		myLogFileSingleDay_Path = myLocalMountDir + "/Mongo_TemperatureLogs/MongoTempLog_SingleDay." + myDateStamp_Today + ".csv"
		logFileSingleDay = open(myLogFileSingleDay_Path, "a")
		logFileSingleDay.write(myFileHeader1)
		logFileSingleDay.write(myFileHeader2)	
		
#	--------------------------------------------
#   Loop through the available sensors (only 2 assumed,
#   for which we experimentally determined their IDs 
#   and hard-coded them into this script)
        
	for mySensor in W1ThermSensor.get_available_sensors():
		curSensorID = mySensor.id
		curTempC = round(float(mySensor.get_temperature()),1)
		myTimeStamp = datetime.datetime.now().strftime("%Y-%m-%[email protected]%H:%M:%S")		

#       ---------------------------------------
#       Identify/assign temp as Case or Shed

		if curSensorID == sensorID_Case:
			myTempCaseC = curTempC
		elif curSensorID == sensorID_Shed:
			myTempShedC = curTempC
		else:
			print("Unexpected SensorID=" + curSensorID)
			
#       ---------------------------------------
#       When we have temps for both inside computer 
#       case and shed, turn heating/cooling on/off
#       accordingly and then write to the 2 logs
#
#       Yes, this will break if/when we do not have
#       both sensors present....

        if curSensorID == sensorID_Shed:
#    	    ---------------------------------------
#           Turn heating/cooling on/of as needed
          
			if myTempCaseC> (caseTempDesiredC + maxDeviation_BeforeCool):
				iO.output(relayHeat, False)
				iO.output(relayCool, True)
				curTempState = tempStateCool
			elif myTempCaseC < (caseTempDesiredC - maxDeviation_BeforeHeat):
				iO.output(relayCool, False)
				iO.output(relayHeat, True)
				curTempState = tempStateHeat
			else:
				iO.output(relayCool, False)
				iO.output(relayHeat, False)
				curTempState = tempStateNone
				
#    	    ---------------------------------------
#     	    Write to the logs, flushing the buffers 
#           of each so we can take a look at the files
#           from another PC even while this script is running
#
#           Why are we getting/logging the Pi's CPU temp?
#           In the immortal words of Alfred E. Neuman "Whyyyyyy not?"
#
#           NB that we check to see if each file is still there
#              and re-create as needed just in case somebody somewhere
#              managed to delete one or both log files at the "right"
#              moment
#
#           NB: The "mountNasDirectiory()" thing is an (unsucessful
#               for now...) attempt to get around mysterious "File 
#               Not Found" errors (Error 02)" if/when somebody on another
#               PC deletes one or both log files while the script is running

			myTempPiC = round(float(getPiCPUtemperature()),1)
			myTempCaseF = round(float(celsiusToFahrenheit(myTempCaseC)))
			myTempShedF = round(float(celsiusToFahrenheit(myTempShedC)))
			myLogFileLine = myLogFileDelim.join(["\n" + myTimeStamp, str(myTempCaseC), str(curTempState), str(myTempShedC), str(myTempShedF), str(myTempPiC)])
						
			if os.path.exists(myLogFileSingleDay_Path):
				logFileSingleDay = open(myLogFileSingleDay_Path, "a")
				logFileSingleDay.write(myLogFileLine)
				logFileSingleDay.close
			else:	
				myLogFileSingleDay_Path = myLocalMountDir + "/Mongo_TemperatureLogs/MongoTempLog_SingleDay." + myDateStamp_Startup + ".csv"				
				mountNasDirectory()
				logFileSingleDay = open(myLogFileSingleDay_Path, "a")					
				logFileSingleDay.write(myFileHeader1)
				logFileSingleDay.write(myFileHeader2)	
				logFileSingleDay.write(myLogFileLine)
				logFileSingleDay.close		
												
			if os.path.exists(myLogFileCumulative_Path):
				logFileCumulative = open(myLogFileCumulative_Path, "a")				
				logFileCumulative.write(myLogFileLine)
				logFileCumulative.close
			else:
				mountNasDirectory()	
				logFileCumulative = open(myLogFileCumulative_Path, "a")					
				logFileCumulative.write(myFileHeader1)
				logFileCumulative.write(myFileHeader2)			
				logFileCumulative.write(myLogFileLine)
				logFileCumulative.close

#     	  	-------------------------------------
#    	  	Just for testing/debugging, print some
#     	  	info on the console

			print("ServerCase=" + str(myTempCaseC) + "C / " + str(myTempCaseF) + "F  Shed=" + str(myTempShedC) + "C / " + str(myTempShedF) + "F   TempState=" + str(curTempState) + "   PiCPU=" + str(myTempPiC) + " at " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) 
   
	time.sleep(secondsBetweenReadings)
#	sys.exit
Here's a paste from my build log on how to get Timo's library:

Code: Select all

15) Add support for installing stuff from GitHub:
	sudo apt-get install git-core

16) Determine which version of Python we are running (2 or 3)
   [email protected]_Pi:~ $ python --version
   Python 2.7.9

17) Install the temp sensing library from GitHub:
   sudo apt-get install python-w1thermsensor

      or, in the unlikely case we somehow have moved
      to Python3:    sudo apt-get install python3-w1thermsensor
Here's the little app I used to discover the sensorIDs:

Code: Select all

# --------------------------------------------------------
# PURPOSE: To feel out the w1thermsensor library

import os
import glob
import time
import datetime
import RPi.GPIO as iO
import os,subprocess
from subprocess import call
from w1thermsensor import W1ThermSensor


os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
 
# -------------------------------------
# Set a pointer to our W1thermsensor object,
# which will give us easy access to the sensor

mySensor = W1ThermSensor()

# -------------------------------------
# Define sensors by ID

sensorID_Case = "0000080222f8"
sensorID_Shed = "04165661cdff"
# -------------------------------------
# Print sensor values

for mySensor in W1ThermSensor.get_available_sensors():
	curSensorID = mySensor.id
	curTemp = mySensor.get_temperature()
	curTemp = round(curTemp,1)
	
	if curSensorID == sensorID_Case:
		myTempCase = curTemp
		print("Case=" + str(myTempCase))
	elif curSensorID == sensorID_Shed:
		myTempShed = curTemp
		print("Shed=" + str(myTempShed))
	else:
		print("Unexpected SensorID=" + curSensorID)
	myTimeStamp = datetime.datetime.now().strftime("%Y-%m-%[email protected]%H:%M:%S")		
	print(curSensorID + " Temp = " + str(curTemp) + " at " + datetime.datetime.now().strftime("%Y-%m-%d %H%M%S")) 

sibir
Posts: 2
Joined: Mon Dec 11, 2017 4:29 pm

Re: Reading multiple DS18B20 with Python

Mon Dec 11, 2017 4:35 pm

Dan,

your DropBox link does not work anymore, any other way I could look at your code?

Thanks,
Martin

Return to “Python”

Who is online

Users browsing this forum: onlinegill and 10 guests