Advertisement
EmptySet5150

Python3 - RPi3 - Auto Garden Watering - Beta V1

Apr 30th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.89 KB | None | 0 0
  1. """
  2.  
  3. Read from database to get last watering info on startup
  4.     Using peewee and SQLite with the model.py
  5.  
  6. Still want to change the way the lcd_display is called
  7.  
  8. """
  9. #Import the GPIO for raspberry pi
  10. import RPi.GPIO as GPIO
  11.  
  12. #Import the pigpio deamon and initalize
  13. #Only used for the DHT22 sensor - Might look for another libary in the future  
  14. import pigpio
  15. pi = pigpio.pi()
  16.  
  17. #Import some more things we need
  18. import DHT22#Temperature and Humidity sensor
  19. from RPLCD import CharLCD#LCD display
  20. from time import sleep
  21. from datetime import datetime
  22. from dateutil.relativedelta import relativedelta#Only used to add days to current date - Look for a way with datetime
  23. from model import SensorData#peewee to SQLite database
  24.  
  25. #Set GPIO modes
  26. GPIO.setmode(GPIO.BOARD)#Set to board numbering
  27.  
  28. #Set variables for GPIO pin numbers - BOARD numbering
  29. database = SensorData()
  30. lcd = CharLCD(cols=20, rows=4, pin_rs=11, pin_e=12, pins_data=[31,33,35,37])
  31. dht22 = DHT22.sensor(pi,22)#This libary is set for GPIO numbering
  32. rainSensor = 40
  33. waterValveControl = 22
  34. pumpControl = 32
  35. lowWater = 16
  36.  
  37. #Set GPIO pin modes
  38. GPIO.setup(waterValveControl,GPIO.OUT)
  39. GPIO.setup(pumpControl,GPIO.OUT)
  40. GPIO.setup(rainSensor,GPIO.IN,pull_up_down=GPIO.PUD_UP)#Using internal pullup resistor
  41. GPIO.setup(lowWater,GPIO.IN,pull_up_down=GPIO.PUD_UP)#Using internal pullup resistor
  42.  
  43. #Setup variables
  44. waitDays = 1#Number of days to wait between waterings
  45. pumpRunTime = 10#How many minutes the pump will run
  46. valveNotOpen = 5#How many minutes to wait to start the pump if the valve fails to open
  47. lowWaterReset = 1#How many days to wait if the tank water level is low
  48. firstRain = 0
  49.  
  50. #Get this variable data from the database
  51. #UNDER CONSTRUCTION
  52. #def get_last_database():
  53. #lastWatered, nextWatering, pumpStopTime = get_last_database()
  54. lastWatered = (datetime.now())
  55. nextWatering = (datetime.now())
  56. pumpStopTime = (datetime.now())
  57.  
  58. #Define a few functions to read a GPIO input and return data
  59. def water_level():
  60.     if GPIO.input(lowWater)==False:
  61.         return 'LOW'
  62.     if GPIO.input(lowWater)==True:#Water level sensor to be figured out later this works now
  63.         return '75'
  64. def rain_sensor():
  65.     if GPIO.input(rainSensor)==False:
  66.         return 'Wet'
  67.     if GPIO.input(rainSensor)==True:
  68.         return 'Dry'
  69. def pump_status():
  70.     if GPIO.input(pumpControl)==False:
  71.         return 'ON'
  72.     if GPIO.input(pumpControl)==True:
  73.         return 'OFF'
  74. def valve_status():
  75.     if GPIO.input(waterValveControl)==False:
  76.         return 'OPEN'
  77.     if GPIO.input(waterValveControl)==True:
  78.         return 'SHUT'
  79.  
  80. #Function returns temperature and humidity readings from DHT22 sensor
  81. def temperature_sensor():
  82.     dht22.trigger()#Reading sensor then waiting First reading is bad data
  83.     sleep(.1)
  84.     temp = '%.1f' % (dht22.temperature() * 1.8 + 32)#C to F converson
  85.     return temp
  86. def humidity_sensor():
  87.     dht22.trigger()#Reading sensor then waiting First reading is bad data
  88.     sleep(.1)
  89.     humidity = '%.1f' % (dht22.humidity())
  90.     return humidity
  91.  
  92. #Function starts or stops the pump and opens or closes the water valve
  93. def pump_control(cont):
  94.     if cont == 'Start':
  95.         print("Opening Valve")
  96.         GPIO.output(waterValveControl,0)
  97.         sleep(5)
  98.         print("Starting Pump")
  99.         GPIO.output(pumpControl,0)
  100.     if cont == 'Stop':
  101.         GPIO.output(pumpControl,1)
  102.         print("Stopping Pump")
  103.         sleep(5)
  104.         print("Closing Valve")
  105.         GPIO.output(waterValveControl,1)
  106.     if cont == 'ERROR':
  107.         GPIO.output(pumpControl,1)
  108.         GPIO.output(waterValveControl,1)
  109.         print("Water Valve Failed to Open")
  110.  
  111. #Reading all the sensors and returning the data
  112. def get_data():
  113.     timenow = (datetime.now().strftime('%d/%m/%y %H:%M'))
  114.     temp = temperature_sensor()
  115.     humid = humidity_sensor()
  116.     pump = pump_status()
  117.     rain = rain_sensor()
  118.     waterlevel = water_level()
  119.     lastwater = lastWatered.strftime('%d/%m %H:%M')
  120.     nextwater = nextWatering.strftime('%d/%m %H:%M')
  121.     valve = valve_status()
  122.     pumpstop = pumpStopTime.strftime('%d/%m %H:%M')
  123.     return timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop
  124.  
  125. #Getting data from get_data and saving it to the database
  126. def save_database():
  127.     timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
  128.     database.saveData(timenow, lastwater, nextwater, pumpstop, temp, humid, waterlevel, rain, pump,valve)
  129.  
  130. #Getting data from get_data and displaying it on the LCD screen
  131. def lcd_display():
  132.     timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
  133.     sleep(5)#Wait then clear and display data
  134.     lcd.clear()
  135.     lcd.cursor_pos = (0,0)
  136.     lcd.write_string("Time: " + timenow)
  137.     lcd.cursor_pos = (1,0)
  138.     lcd.write_string("Temp " + temp)
  139.     lcd.cursor_pos = (1,10)
  140.     lcd.write_string("Humid " + humid)
  141.     lcd.cursor_pos = (2,0)
  142.     lcd.write_string("Pump:" + pump)   
  143.     lcd.cursor_pos = (2,10)
  144.     lcd.write_string("Valve:" + valve)
  145.     lcd.cursor_pos = (3,0)
  146.     lcd.write_string("LstWater:" + lastwater)
  147.     sleep(5)#We wait and then clear the screen to display more data
  148.     lcd.clear()
  149.     lcd.cursor_pos = (0,0)
  150.     lcd.write_string("Time: " + timenow)
  151.     lcd.cursor_pos = (1,0)
  152.     lcd.write_string("Temp " + temp)
  153.     lcd.cursor_pos = (1,10)
  154.     lcd.write_string("Humid " + humid)
  155.     lcd.cursor_pos = (2,0)
  156.     lcd.write_string("Rain:" + rain)
  157.     lcd.cursor_pos = (2,12)
  158.     lcd.write_string("Tank:" + waterlevel)
  159.     lcd.cursor_pos = (3,0)
  160.     lcd.write_string("NxtWater:" + nextwater)
  161.    
  162. #Getting data from get_data and printing it to terminal window
  163. def print_data():
  164.     timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
  165.     print("    -----START-----")
  166.     print('Temperature    -- ' + (temp) + 'F')
  167.     print('Humidity       -- ' + (humid) + '%')
  168.     print('Pump Status    -- ' + (pump))
  169.     print('Water Valve    -- ' + (valve))
  170.     print('Rain Sensor    -- ' + (rain))
  171.     print('Water Level    -- ' + (waterlevel))
  172.     print('Time Now       -- ' + (datetime.now().strftime('%d/%m/%y %H:%M:%S')))
  173.     print('Last Watered   -- ' + (lastwater))
  174.     print('Pump Stop Time -- ' + (pumpstop))
  175.     print('Next Watering  -- ' + (nextwater))
  176.     print("    ------END------")
  177.  
  178. #Main loop
  179. try:
  180.     while True:
  181.         lcd_display()
  182.         print_data()
  183.         print("Main Loop Display")
  184. #If the time is on a 10 save the get_data to the database and print to terminal
  185.         if int(datetime.now().strftime('%M')) in (00,10,20,30,40,50):
  186.             print_data()
  187.             save_database()
  188.             sleep(45)#45 second delay so I only get 1 reading every 10 min
  189.             print("Saved data to database - MAIN LOOP")
  190. #If the rain sensor is wet we reset the nextWatering and lastWatered time
  191.         if rain_sensor() == 'Wet':#Rain sensor is wet so we set latsWatered
  192.             print("Its Raining")
  193.             lastWatered = datetime.now()
  194.             addDays = datetime.now() + relativedelta(days=waitDays)#Add waitDays to current time
  195.             nextWatering = addDays.replace(hour=21,minute=0,second=0)#Change hour to 21:00 - 9pm
  196. #If this is the first time the sensor was wet sence the last time it was dry save to database
  197.             if firstRain == 0:
  198.                 firstRain = firstRain + 1
  199.                 save_database()
  200.                 print("Saved data to database - RAIN SENSOR")
  201. #Set firstRain to 0 when its not raining               
  202.         else:
  203.             firstRain = 0
  204.             print("Its Not Raining")
  205. #If water level is to low we reset nextWatering to the next day    
  206.         if water_level() == 'LOW':
  207.             print("Water Level is LOW")
  208.             lowWater = datetime.now() + relativedelta(days=lowWaterReset)#Add lowWaterReset to current time
  209.             nextWatering = lowWater.replace(hour=21,minute=0,second=0)#Change hour to 21:00 - 9pm
  210. #If the pump is off we check to see if its time to turn it on
  211.         if pump_status() == 'OFF':
  212.             if datetime.now() >= nextWatering:
  213. #Then we update the lastWatered and pumpStopTime
  214.                 pumpStopTime = datetime.now() + relativedelta(minutes=pumpRunTime)#Add pumpRunTime to current time
  215.                 print("Time to Start pump")
  216.                 pump_control('Start')
  217. #We also check to see if the valve is closed and return a error if the valve is SHUT
  218.                 if valve_status() == 'SHUT':
  219.                     print("Valve is CLOSED - Unable to Start")
  220.                     pump_control('ERROR')
  221.                     nextWatering = lastWatering + relativedelta(minutes=valveNotOpen)#Add valveNotOpen to current time
  222. #If the pump is on we check to see if it is time to turn it off and update nextWatering    
  223.         if pump_status() == 'ON':
  224.             lastWatering = datetime.now()
  225.             adddays = datetime.now() + relativedelta(days=waitDays)#Add waitDays to current time
  226.             nextWatering = adddays.replace(hour=21,minute=0,second=0)#Change hour to 21:00 - 9pm
  227.             if datetime.now() >= pumpStopTime:
  228.                 print("Time to Stop Pump")
  229.                 pump_control('Stop')
  230. #We also check to see if it started raining
  231.             if rain_sensor() == 'Wet':
  232.                 print("It started raining")
  233.                 pump_control('Stop')
  234. #We also check to see if the water level is low
  235.             if water_level() == 'LOW':
  236.                 print("Water Level got to LOW")
  237.                 pump_control('Stop')
  238.  
  239. #When program ends or is interupted we cleanup the GPIO pins
  240. finally:
  241.     print("Shutdown")
  242.     database.close()
  243.     print("Closed database")
  244.     GPIO.cleanup()
  245.     print("GPIO pins cleanup")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement