Mvlawn
Posts: 11
Joined: Sat Jan 03, 2015 6:34 pm

Combining 2 tutorials

Tue Apr 07, 2015 5:58 pm

Hello All. I have completed a couple tutorials and I wanted to combine them. I have completed the logging temps with DHT11 and logging them onto Google docs, and I have completed the 1 wire thermometer with success as well. Links provided below. My next challenge was to combine the 2 projects. I have done this semi successfully. when i run the program the first temp i see is the Dallas temp but it never repeats, the DHT11 however keeps spitting out temp and humidity. What am i doing wrong that it doesn't repeat




https://learn.adafruit.com/dht-humidity ... g?view=all
http://www.raspberrypi-spy.co.uk/2013/0 ... er-sensor/

Code: Select all

#!/usr/bin/python


# SOFTWARE.
import sys
import time
import datetime

import Adafruit_DHT
import gspread

# Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHT_TYPE = Adafruit_DHT.DHT11

# Example of sensor connected to Raspberry Pi pin 23
DHT11_PIN  = 23


# Google Docs account email, password, and spreadsheet name.
GDOCS_EMAIL            = 'my email goes here'
GDOCS_PASSWORD         = 'my pass word goes here'
GDOCS_SPREADSHEET_NAME = 'DHT Humidity Logs'

# How long to wait (in seconds) between measurements.
FREQUENCY_SECONDS      = 15


def login_open_sheet(email, password, spreadsheet):
	"""Connect to Google Docs spreadsheet and return the first worksheet."""
	try:
		gc = gspread.login(email, password)
		worksheet = gc.open(spreadsheet).sheet1
		return worksheet
	except:
		print 'Unable to login and get spreadsheet.  Check email, password, spreadsheet name.'
		sys.exit(1)
#start of dallas script

#!/usr/bin/python
#--------------------------------------
#
#              ds18b20.py
#  Read DS18B20 1-wire temperature sensor
#
# Author : Matt Hawkins
# Date   : 10/02/2015
#
# http://www.raspberrypi-spy.co.uk/
#
#--------------------------------------

def gettemp(id):
  try:
    mytemp = ''
    filename = 'w1_slave'
    f = open('/sys/bus/w1/devices/' + id + '/' + filename, 'r')
    line = f.readline() # read 1st line
    crc = line.rsplit(' ',1)
    crc = crc[1].replace('\n', '')
    if crc=='YES':
      line = f.readline() # read 2nd line
      mytemp = line.rsplit('t=',1)
    else:
      mytemp = 99999
    f.close()

    return int(mytemp[1])

  except:
    return 99999

if __name__ == '__main__':

  # Script has been called directly
  id = '28-00000657a569'
  print "Temp : " + '{:.3f}'.format(gettemp(id)/float(1000))






#end of dallas script




print 'Logging sensor measurements to {0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS)
print 'Press Ctrl-C to quit.'
worksheet = None
while True:
	# Login if necessary.
	if worksheet is None:
		worksheet = login_open_sheet(GDOCS_EMAIL, GDOCS_PASSWORD, GDOCS_SPREADSHEET_NAME)

	# Attempt to get sensor reading.
	humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT11_PIN)

	# Skip to the next reading if a valid measurement couldn't be taken.
	# This might happen if the CPU is under a lot of load and the sensor
	# can't be reliably read (timing is critical to read the sensor).
	if humidity is None or temp is None:
		time.sleep(2)
		continue

	print 'Temperature: {0:0.1f} C'.format(temp)
	print 'Humidity:    {0:0.1f} %'.format(humidity)
             
 
	# Append the data in the spreadsheet, including a timestamp
	try:
		worksheet.append_row((datetime.datetime.now(), temp, humidity))
	except:
		# Error appending data, most likely because credentials are stale.
		# Null out the worksheet so a login is performed at the top of the loop.
		print 'Append error, logging in again'
		worksheet = None
		time.sleep(FREQUENCY_SECONDS)
		continue

	# Wait 30 seconds before continuing
	print 'Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME)
	time.sleep(FREQUENCY_SECONDS)

Mvlawn
Posts: 11
Joined: Sat Jan 03, 2015 6:34 pm

Re: Combining 2 tutorials

Tue Apr 07, 2015 6:05 pm

I forgot to add the screen shot. [img]file:///home/pi/Desktop/2015-04-07-135221_1776x952_scrot.png
[/img]

DirkS
Posts: 9902
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: Combining 2 tutorials

Tue Apr 07, 2015 6:09 pm

Mvlawn wrote:I forgot to add the screen shot. [img]file:///home/pi/Desktop/2015-04-07-135221_1776x952_scrot.png
[/img]
That's a link to a file on your Pi. You'll need to upload it, probably to a 3rd party site, and then post a link.

JF002
Posts: 94
Joined: Sat Feb 04, 2012 8:49 am
Contact: Website

Re: Combining 2 tutorials

Tue Apr 07, 2015 6:35 pm

From what I can see, you have merged 2 python scripts into a single one.
Now, you'll have to rearrange some things in order to make it work the way you want.

First you can remove the line

Code: Select all

#!/usr/bin/python
(on line 39), because it is already specified on line 1.

Then, what happens when you execute your script?
Python loads it, find the definition of the function gettemp(), but does not run it.

Then, on line 72, it checks if the script has been called directly (not from another python module).
In this case, it will execute line 75-76:

Code: Select all

  id = '28-00000657a569'
  print "Temp : " + '{:.3f}'.format(gettemp(id)/float(1000))
In short, it prints one time the result of the function gettemp() on the console.

After that, python continue reading the script, and executes all the remaining code, mainly composed of a infinite loop, on line 91:

Code: Select all

while True:
    ...
This loop seems to read something from 'Adafruit_DHT', do some computations, print result on the console, and do something with this 'worksheet' (logging on Google Doc, I assume).
As this is an infinite loop, it will do this forever.

So, as I understand it, your script will print one time the result of the function 'gettemp()', and then it will print and log forever the result of 'Adafruit_DHT.read(DHT_TYPE, DHT11_PIN)'.

If you want to print the result of gettemp() repeatedly, you should move lines 75-76 into the 'while' loop.
My web site : https://codingfield.com

Mvlawn
Posts: 11
Joined: Sat Jan 03, 2015 6:34 pm

Re: Combining 2 tutorials

Tue Apr 07, 2015 7:49 pm

JF002 your comments worked. I had to move the print temp to line 112 for it to work in the loop. Thanks so much!!! I appreciate your time as that was no quick 2 sentence response.

I assume I have to rename the Temp Line113 to something else so that

Code: Select all

id = '28-00000657a569'
  	print "Temp : " + '{:.3f}'.format(gettemp(id)/float(1000))
I can use it in my append string Line 118 to have it print to the spreadsheet
worksheet.append_row((datetime.datetime.now(), temp, humidity))

Code: Select all

#!/usr/bin/python


# SOFTWARE.
import sys
import time
import datetime

import Adafruit_DHT
import gspread

# Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHT_TYPE = Adafruit_DHT.DHT11

# Example of sensor connected to Raspberry Pi pin 23
DHT11_PIN  = 23


# Google Docs account email, password, and spreadsheet name.
GDOCS_EMAIL            = ''
GDOCS_PASSWORD         = ''
GDOCS_SPREADSHEET_NAME = 'DHT Humidity Logs'

# How long to wait (in seconds) between measurements.
FREQUENCY_SECONDS      = 15


def login_open_sheet(email, password, spreadsheet):
	"""Connect to Google Docs spreadsheet and return the first worksheet."""
	try:
		gc = gspread.login(email, password)
		worksheet = gc.open(spreadsheet).sheet1
		return worksheet
	except:
		print 'Unable to login and get spreadsheet.  Check email, password, spreadsheet name.'
		sys.exit(1)
#start of dallas script


#--------------------------------------
#
#              ds18b20.py
#  Read DS18B20 1-wire temperature sensor
#
# Author : Matt Hawkins
# Date   : 10/02/2015
#
# http://www.raspberrypi-spy.co.uk/
#
#--------------------------------------

def gettemp(id):
  try:
    mytemp = ''
    filename = 'w1_slave'
    f = open('/sys/bus/w1/devices/' + id + '/' + filename, 'r')
    line = f.readline() # read 1st line
    crc = line.rsplit(' ',1)
    crc = crc[1].replace('\n', '')
    if crc=='YES':
      line = f.readline() # read 2nd line
      mytemp = line.rsplit('t=',1)
    else:
      mytemp = 99999
    f.close()

    return int(mytemp[1])

  except:
    return 99999

if __name__ == '__main__':

  # Script has been called directly
  id = '28-00000657a569'
  print "Temp : " + '{:.3f}'.format(gettemp(id)/float(1000))






#end of dallas script




print 'Logging sensor measurements to {0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS)
print 'Press Ctrl-C to quit.'
worksheet = None
while True:
	# Login if necessary.
	if worksheet is None:
		worksheet = login_open_sheet(GDOCS_EMAIL, GDOCS_PASSWORD, GDOCS_SPREADSHEET_NAME)

	# Attempt to get sensor reading.
	humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT11_PIN)



	# Skip to the next reading if a valid measurement couldn't be taken.
	# This might happen if the CPU is under a lot of load and the sensor
	# can't be reliably read (timing is critical to read the sensor).
	if humidity is None or temp is None:
		time.sleep(2)
		continue

	print 'Temperature: {0:0.1f} C'.format(temp)
	print 'Humidity:    {0:0.1f} %'.format(humidity)


	id = '28-00000657a569'
  	print "Temp : " + '{:.3f}'.format(gettemp(id)/float(1000))
             
 
	# Append the data in the spreadsheet, including a timestamp
	try:
		worksheet.append_row((datetime.datetime.now(), temp, humidity))
	except:
		# Error appending data, most likely because credentials are stale.
		# Null out the worksheet so a login is performed at the top of the loop.
		print 'Append error, logging in again'
		worksheet = None
		time.sleep(FREQUENCY_SECONDS)
		continue

	# Wait 30 seconds before continuing
	print 'Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME)
	time.sleep(FREQUENCY_SECONDS)

JF002
Posts: 94
Joined: Sat Feb 04, 2012 8:49 am
Contact: Website

Re: Combining 2 tutorials

Tue Apr 07, 2015 8:06 pm

You can store the result of gettemp() in a variable in order to use it later:

Code: Select all

# As an integer
tempDS18B20 = gettemp(id)/float(1000)
# As a String
tempDS18B20 = '{:.3f}'.format(gettemp(id)/float(1000)) 
My web site : https://codingfield.com

Mvlawn
Posts: 11
Joined: Sat Jan 03, 2015 6:34 pm

Re: Combining 2 tutorials

Tue Apr 07, 2015 9:10 pm

JF002

Thank You that worked.

Return to “General programming discussion”