-
-
Save darkmanlv/47d6b5266f5767bd992131cdaf69088e to your computer and use it in GitHub Desktop.
This script periodically polls the AM2302 (DHT11) sensor for Temperature and humidity data, logs it locally to a csv file and also sends the data to ThingSpeak. Script is working on Python3.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Based on Humidity and Temperature data logging script by Anurag Kotha | |
Updated 10.03.2022 - now script is working with Python3 on raspberry pi | |
""" | |
# Import all the libraries we need to run | |
import sys | |
import os | |
import time | |
import Adafruit_DHT | |
import urllib.request, urllib.error, urllib.parse | |
pwd = "/home/pi/TempHum/" | |
DEBUG = 0 | |
# Setup the pins we are connected to | |
DHTpin = 4 | |
#Setup our API and delay | |
myAPI = "YOUR_API_KEY" # *** SET YOUR API KEY HERE. WONT WORK OTHERWISE | |
myDelay = 180 #how many seconds between posting data | |
# File name for data logging | |
fname = pwd + 'TemHumLog_'+time.strftime("%d%m%Y", time.gmtime()) + '.csv' | |
# File name for error recovery | |
fErrRec = pwd + 'TempHumErrorStatus.log' | |
def getSensorData(): | |
RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, DHTpin) # Change AM2302 to DHT11 if you have DHT11 sensor | |
#Convert from Celius to Farenheit | |
TWF = 9/5*TW+32 | |
# return dict | |
return (str(RHW), str(TW),str(TWF)) | |
# main() function | |
def main(): | |
print('starting... ') | |
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI | |
print (baseURL) | |
while True: | |
try: | |
mTime = time.strftime("%d/%m/%Y %H:%M:%S",time.gmtime()) | |
RHW, TW, TWF = getSensorData() | |
# Log data to file | |
mData = "%s,%s,%s,%s\n" %(mTime,TW,TWF,RHW) | |
logfile = open(fname,'a') | |
logfile.write(mData) | |
logfile.close() | |
print ("Time " + mTime," Temperature C " + TW + " Temperature F " + TWF + " Humidity " + RHW) | |
# Log error status to file | |
logfile = open(fErrRec,'a') | |
logfile.write("1\n") | |
logfile.close() | |
time.sleep(int(myDelay)) | |
except: | |
# Log error status to file | |
logfile = open(fErrRec,'a') | |
logfile.write("0\n") | |
logfile.close() | |
print('Exception caught') | |
# break Dont want to exit everytime we loose network connection. | |
try: | |
# Send data to ThingSpeak takes some time to open the connection | |
f = urllib.request.urlopen(baseURL + "&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+ "&field4=%s" % ('1')) | |
except: | |
# Log error status to file | |
logfile = open(fErrRec,'a') | |
logfile.write("0") | |
logfile.close() | |
print ('Failed to connect to the server.') | |
# call main | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment