Skip to content

Instantly share code, notes, and snippets.

@li2hub
Created February 15, 2019 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save li2hub/b28d25048ae4bd8f60388183fcae4e3a to your computer and use it in GitHub Desktop.
Save li2hub/b28d25048ae4bd8f60388183fcae4e3a to your computer and use it in GitHub Desktop.
import sys
import RPi.GPIO as GPIO
import os
from time import sleep
import Adafruit_DHT
import urllib2
DEBUG = 1
# Setup the pins we are connect to
soilpin = 14
DHTpin = 23
#Setup our API and delay
myAPI = "***Insert Your API CODE HERE***" # Thingspeak WRITE API Key
myDelay = 15 #how many seconds between posting data
GPIO.setmode(GPIO.BCM)
GPIO.setup(soilpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def getSensorData():
RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)
#Convert from Celius to Farenheit
TWF = 9/5*TW+32
# return dict
return (str(RHW), str(TW),str(TWF))
# Test the soil moisture level
def soiltime(soilpin):
ST= 0
if (GPIO.input(soilpin) == True):
ST += 1
print 'I have enough water'
else:
print 'I am thirsty'
return (str(ST))
# main() function, this part measures and send the data to thinkgspeak
def main():
print 'starting...'
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
print baseURL
while True:
try:
RHW, TW, TWF = getSensorData()
ST = soiltime(soilpin)
f = urllib2.urlopen(baseURL +
"&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+
"&field4=%s" % (ST))
print f.read()
print TW + " " + TWF+ " " + RHW + " " + ST
f.close()
sleep(int(myDelay))
except:
print 'exiting.'
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment