Advertisement
EmptySet5150

Python3 - RPi3 - Auto Garden Watering - Beta V2

May 23rd, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.81 KB | None | 0 0
  1. """
  2. This program  gets data from several sensors
  3. to  determine  when the  garden needs  to be
  4. watered. When it needs watering it will turn
  5. on a pump and  open a valve for a set amount
  6. of time to water the garden. If it starts to
  7. rain  or the  water level  gets low the pump
  8. will shut off and rest to  the next watering
  9. date.
  10. """
  11.  
  12. # Lets import a few things needed for the system
  13. from RPLCD import CharLCD  # Libaray for the LCD screen
  14. from time import sleep
  15. from datetime import datetime
  16. from dateutil.relativedelta import relativedelta  # Only used to add days to current date
  17. from model import SensorData  # Using peewee to interface with a SQLite database
  18. import RPi.GPIO as GPIO
  19. import DHT22  # Used for Temperature and Humidity sensor
  20. import pigpio  # Only used for DHT22 sensor - Looking into another library
  21.  
  22. pi = pigpio.pi()  # Only used for DHT22 sensor - Looking into another library
  23.  
  24. # Setup pin names
  25. GPIO.setmode(GPIO.BOARD)  # Setting the pin number
  26. lcd = CharLCD(cols=20, rows=4, pin_rs=11, pin_e=12, pins_data=[31, 33, 35, 37])
  27. dht22 = DHT22.sensor(pi, 22)  # This library is setup for GPIO numbering
  28. rainSensor = 40
  29. waterValveControl = 22
  30. pumpControl = 32
  31. waterLevel = 16
  32. sensorDatabase = SensorData()
  33.  
  34. # Setup GPIO pin modes
  35. GPIO.setup(waterValveControl, GPIO.OUT)  # Set pin as output
  36. GPIO.setup(pumpControl, GPIO.OUT)  # Set pin as output
  37. GPIO.setup(rainSensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Set pin as input and use internal pull up resistor
  38. GPIO.setup(waterLevel, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Set pin as imput and use internal pull up resistor
  39.  
  40. # Setup some global variables
  41. waitDays = int(input("How many days to wait between waterings? "))
  42. pumpRunTime = int(input("How many minutes for the pump to run? "))
  43. valveNotOpen = int(input("How many minutes to wait to restart if the valve failes to open? "))
  44. lowWaterReset = int(input("How many days to wait if the water tank is low? "))
  45. firstRain = 1  # Setting this so we only get one reading while its raining
  46. firstLowWater = 1  # Setting this so we only get one reading while water level is low
  47.  
  48. # This data should get from the database
  49. lastWatered = (datetime.now())
  50. nextWatering = (datetime.now())
  51. pumpStopTime = (datetime.now())
  52.  
  53.  
  54. # Functions to return temperature and humidity readings from the DHT22 sensor
  55. def temperature_status():
  56.     dht22.trigger()  # Read the sensor then wait because the first reading is null
  57.     sleep(.2)
  58.     temp = '%.1f' % (dht22.temperature() * 1.8 + 32)  # Converting C to F and taking it out to one decimal place
  59.     return temp
  60.  
  61.  
  62. def humidity_status():
  63.     dht22.trigger()
  64.     sleep(.2)
  65.     humid = '%.1f' % (dht22.humidity())  # Taking the humidity out to one decimal place
  66.     return humid
  67.  
  68.  
  69. # Function starts or stops the pump and opens or closes the water valve and returns its status
  70. def pump_control(cont):
  71.     if cont == 'Start':
  72.         print("Opening Valve")
  73.         GPIO.output(waterValveControl, 0)
  74.         sleep(5)
  75.         print("Starting Pump")
  76.         GPIO.output(pumpControl, 0)
  77.     elif cont == 'Stop':
  78.         print("Stopping Pump")
  79.         GPIO.output(pumpControl, 1)
  80.         sleep(5)
  81.         print("Closing Valve")
  82.         GPIO.output(waterValveControl, 1)
  83.     elif cont == 'ERROR':
  84.         GPIO.output(pumpControl, 1)
  85.         GPIO.output(waterValveControl, 1)
  86.         print("Water valve failed to open")
  87.  
  88.  
  89. # Functions read the GPIO pins to determine if they are on or off and return a status
  90. def water_status():
  91.     if GPIO.input(waterLevel) == False:
  92.         return 9
  93.     elif GPIO.input(waterLevel) == True:
  94.         return 77
  95.  
  96.  
  97. def rain_status():
  98.     if GPIO.input(rainSensor) == False:
  99.         return 'WET'
  100.     elif GPIO.input(rainSensor) == True:
  101.         return 'DRY'
  102.  
  103.  
  104. def pump_status():
  105.     if GPIO.input(pumpControl) == False:
  106.         return 'ON'
  107.     elif GPIO.input(pumpControl) == True:
  108.         return 'OFF'
  109.  
  110.  
  111. def valve_status():
  112.     if GPIO.input(waterValveControl) == False:
  113.         return 'OPEN'
  114.     elif GPIO.input(waterValveControl) == True:
  115.         return 'SHUT'
  116.  
  117.  
  118. # Function reads the data from all the senors and returns it
  119. def get_data():
  120.     timenow = (datetime.now().strftime('%d/%h/%m %H:%M'))
  121.     temp = temperature_status()
  122.     humid = humidity_status()
  123.     pump = pump_status()
  124.     rain = rain_status()
  125.     waterlevel = water_status()
  126.     lastwater = lastWatered.strftime('%d/%m/%y %H:%M')
  127.     nextwater = nextWatering.strftime('%d/%m/%y %H:%M')
  128.     valve = valve_status()
  129.     pumpstop = pumpStopTime.strftime('%d/%m/%y %H:%M')
  130.     return timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop
  131.  
  132.  
  133. # Function gets data from get_data() and saves it to the database
  134. def save_database():
  135.     timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
  136.     sensorDatabase.saveData(timenow, lastwater, nextwater, pumpstop, temp, humid, waterlevel, rain, pump, valve)
  137.  
  138.  
  139. # Function gets data from get_data and displays it on the LCD screen
  140. def lcd_display():
  141.     timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
  142.     sleep(5)  # Wait then clear the display
  143.     lcd.clear()
  144.     lcd.cursor_pos = (0, 0)
  145.     lcd.write_string("Time: " + timenow)
  146.     lcd.cursor_pos = (1, 0)
  147.     lcd.write_string("Temp " + temp)
  148.     lcd.cursor_pos = (1, 10)
  149.     lcd.write_string("Humid " + humid)
  150.     lcd.cursor_pos = (2, 0)
  151.     lcd.write_string("Pump:" + pump)
  152.     lcd.cursor_pos = (2, 10)
  153.     lcd.write_string("Valve:" + valve)
  154.     lcd.cursor_pos = (3, 0)
  155.     lcd.write_string("LstWater:" + lastwater)
  156.     sleep(5)  # We wait and then clear the screen to display more data
  157.     waterlevelstr = str(waterlevel)
  158.     lcd.clear()
  159.     lcd.cursor_pos = (0, 0)
  160.     lcd.write_string("Time: " + timenow)
  161.     lcd.cursor_pos = (1, 0)
  162.     lcd.write_string("Temp " + temp)
  163.     lcd.cursor_pos = (1, 10)
  164.     lcd.write_string("Humid " + humid)
  165.     lcd.cursor_pos = (2, 0)
  166.     lcd.write_string("Rain:" + rain)
  167.     lcd.cursor_pos = (2, 12)
  168.     lcd.write_string("Tank:" + waterlevelstr)
  169.     lcd.cursor_pos = (3, 0)
  170.     lcd.write_string("NxtWater:" + nextwater)
  171.  
  172.  
  173. # Function gets data from get_data() and print is to the terminal window
  174. def print_data():
  175.     timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
  176.     waterlevelstr = str(waterlevel)
  177.     print("    -----START-----")
  178.     print('Temperature    -- ' + temp + 'F')
  179.     print('Humidity       -- ' + humid + '%')
  180.     print('Pump Status    -- ' + pump)
  181.     print('Water Valve    -- ' + valve)
  182.     print('Rain Sensor    -- ' + rain)
  183.     print('Water Level    -- ' + waterlevelstr)
  184.     print('Time Now       -- ' + (datetime.now().strftime('%d/%m/%y %H:%M:%S')))
  185.     print('Last Watered   -- ' + lastwater)
  186.     print('Pump Stop Time -- ' + pumpstop)
  187.     print('Next Watering  -- ' + nextwater)
  188.     print("    ------END------")
  189.  
  190.  
  191. try:
  192.     while True:
  193.         lcd_display()
  194.         print_data()
  195.         print("Main loop display")
  196.         print("FirstLowWater " + str(firstLowWater))
  197.         print("FirstRain " + str(firstRain))
  198.         # If the rain sensor is wet we reset the nextWatering and lastWatered time
  199.         if firstRain == 1 and rain_status() == 'Wet':
  200.             firstRain = (firstRain) + 1
  201.             print("Its Raining")
  202.             pump_control('Stop')
  203.             lastWatered = datetime.now()
  204.             addDays = datetime.now() + relativedelta(days=waitDays)
  205.             nextWatering = addDays.replace(hour=21, minute=00, second=00)
  206.             save_database()
  207.             print("Saved data to database - RAIN SENSOR")
  208.         if firstRain > 1 and rain_status() == 'Dry':
  209.             firstRain = 1
  210.             print("Its Not Raining")
  211.  
  212.         # If water level is to low we reset nextWatering to the next day
  213.         if firstLowWater == 1 and water_status() < 10:
  214.             firstLowWater = (firstLowWater) + 1
  215.             print("Water Level is LOW")
  216.             pump_control('Stop')
  217.             lowWater = datetime.now() + relativedelta(days=lowWaterReset)
  218.             nextWatering = lowWater.replace(hour=21, minute=00, second=00)
  219.             save_database()
  220.             print("Saved to database - LOW WATER SENSOR")
  221.         if firstLowWater > 1 and water_status() >= 10:
  222.             firstLowWater = 1
  223.             print("Water level is okay")
  224.  
  225.         # If the pump is off we check to see if its time to turn it on
  226.         if pump_status() == 'OFF' and datetime.now() >= nextWatering:
  227.             pumpStopTime = datetime.now() + relativedelta(minutes=pumpRunTime)
  228.             print("Time to Start pump")
  229.             pump_control('Start')
  230.             save_database()
  231.             print("Saved to database - PUMP ON")
  232.  
  233.             # We also check to see if the valve is closed and return a error if the valve is SHUT
  234.             if valve_status() == 'SHUT':
  235.                 print("Valve is CLOSED - Unable to Start")
  236.                 pump_control('ERROR')
  237.                 nextWatering = lastWatered + relativedelta(minutes=valveNotOpen)
  238.                 save_database()
  239.                 print("Saved to database - VALVE ERROR")
  240.  
  241.         # If the pump is on we check to see if it is time to turn it off and update nextWatering
  242.         if pump_status() == 'ON' and datetime.now() >= pumpStopTime:
  243.             lastWatering = datetime.now()
  244.             addDays = datetime.now() + relativedelta(days=waitDays)
  245.             nextWatering = addDays.replace(hour=21, minute=0, second=0)
  246.             print("Pump was turned off")
  247.             pump_control('Stop')
  248.             save_database()
  249.             print("Saved to database - PUMP STOP TIME")        
  250.  
  251. # When program ends or is interupted we cleanup the GPIO pins
  252. finally:
  253.     print("Shutdown")
  254.     sensorDatabase.close()
  255.     print("Closed database")
  256.     GPIO.cleanup()
  257.     print("GPIO pins cleanup")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement