Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Read from database to get last watering info on startup
- Using peewee and SQLite with the model.py
- Still want to change the way the lcd_display is called
- """
- #Import the GPIO for raspberry pi
- import RPi.GPIO as GPIO
- #Import the pigpio deamon and initalize
- #Only used for the DHT22 sensor - Might look for another libary in the future
- import pigpio
- pi = pigpio.pi()
- #Import some more things we need
- import DHT22#Temperature and Humidity sensor
- from RPLCD import CharLCD#LCD display
- from time import sleep
- from datetime import datetime
- from dateutil.relativedelta import relativedelta#Only used to add days to current date - Look for a way with datetime
- from model import SensorData#peewee to SQLite database
- #Set GPIO modes
- GPIO.setmode(GPIO.BOARD)#Set to board numbering
- #Set variables for GPIO pin numbers - BOARD numbering
- database = SensorData()
- lcd = CharLCD(cols=20, rows=4, pin_rs=11, pin_e=12, pins_data=[31,33,35,37])
- dht22 = DHT22.sensor(pi,22)#This libary is set for GPIO numbering
- rainSensor = 40
- waterValveControl = 22
- pumpControl = 32
- lowWater = 16
- #Set GPIO pin modes
- GPIO.setup(waterValveControl,GPIO.OUT)
- GPIO.setup(pumpControl,GPIO.OUT)
- GPIO.setup(rainSensor,GPIO.IN,pull_up_down=GPIO.PUD_UP)#Using internal pullup resistor
- GPIO.setup(lowWater,GPIO.IN,pull_up_down=GPIO.PUD_UP)#Using internal pullup resistor
- #Setup variables
- waitDays = 1#Number of days to wait between waterings
- pumpRunTime = 10#How many minutes the pump will run
- valveNotOpen = 5#How many minutes to wait to start the pump if the valve fails to open
- lowWaterReset = 1#How many days to wait if the tank water level is low
- firstRain = 0
- #Get this variable data from the database
- #UNDER CONSTRUCTION
- #def get_last_database():
- #lastWatered, nextWatering, pumpStopTime = get_last_database()
- lastWatered = (datetime.now())
- nextWatering = (datetime.now())
- pumpStopTime = (datetime.now())
- #Define a few functions to read a GPIO input and return data
- def water_level():
- if GPIO.input(lowWater)==False:
- return 'LOW'
- if GPIO.input(lowWater)==True:#Water level sensor to be figured out later this works now
- return '75'
- def rain_sensor():
- if GPIO.input(rainSensor)==False:
- return 'Wet'
- if GPIO.input(rainSensor)==True:
- return 'Dry'
- def pump_status():
- if GPIO.input(pumpControl)==False:
- return 'ON'
- if GPIO.input(pumpControl)==True:
- return 'OFF'
- def valve_status():
- if GPIO.input(waterValveControl)==False:
- return 'OPEN'
- if GPIO.input(waterValveControl)==True:
- return 'SHUT'
- #Function returns temperature and humidity readings from DHT22 sensor
- def temperature_sensor():
- dht22.trigger()#Reading sensor then waiting First reading is bad data
- sleep(.1)
- temp = '%.1f' % (dht22.temperature() * 1.8 + 32)#C to F converson
- return temp
- def humidity_sensor():
- dht22.trigger()#Reading sensor then waiting First reading is bad data
- sleep(.1)
- humidity = '%.1f' % (dht22.humidity())
- return humidity
- #Function starts or stops the pump and opens or closes the water valve
- def pump_control(cont):
- if cont == 'Start':
- print("Opening Valve")
- GPIO.output(waterValveControl,0)
- sleep(5)
- print("Starting Pump")
- GPIO.output(pumpControl,0)
- if cont == 'Stop':
- GPIO.output(pumpControl,1)
- print("Stopping Pump")
- sleep(5)
- print("Closing Valve")
- GPIO.output(waterValveControl,1)
- if cont == 'ERROR':
- GPIO.output(pumpControl,1)
- GPIO.output(waterValveControl,1)
- print("Water Valve Failed to Open")
- #Reading all the sensors and returning the data
- def get_data():
- timenow = (datetime.now().strftime('%d/%m/%y %H:%M'))
- temp = temperature_sensor()
- humid = humidity_sensor()
- pump = pump_status()
- rain = rain_sensor()
- waterlevel = water_level()
- lastwater = lastWatered.strftime('%d/%m %H:%M')
- nextwater = nextWatering.strftime('%d/%m %H:%M')
- valve = valve_status()
- pumpstop = pumpStopTime.strftime('%d/%m %H:%M')
- return timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop
- #Getting data from get_data and saving it to the database
- def save_database():
- timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
- database.saveData(timenow, lastwater, nextwater, pumpstop, temp, humid, waterlevel, rain, pump,valve)
- #Getting data from get_data and displaying it on the LCD screen
- def lcd_display():
- timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
- sleep(5)#Wait then clear and display data
- lcd.clear()
- lcd.cursor_pos = (0,0)
- lcd.write_string("Time: " + timenow)
- lcd.cursor_pos = (1,0)
- lcd.write_string("Temp " + temp)
- lcd.cursor_pos = (1,10)
- lcd.write_string("Humid " + humid)
- lcd.cursor_pos = (2,0)
- lcd.write_string("Pump:" + pump)
- lcd.cursor_pos = (2,10)
- lcd.write_string("Valve:" + valve)
- lcd.cursor_pos = (3,0)
- lcd.write_string("LstWater:" + lastwater)
- sleep(5)#We wait and then clear the screen to display more data
- lcd.clear()
- lcd.cursor_pos = (0,0)
- lcd.write_string("Time: " + timenow)
- lcd.cursor_pos = (1,0)
- lcd.write_string("Temp " + temp)
- lcd.cursor_pos = (1,10)
- lcd.write_string("Humid " + humid)
- lcd.cursor_pos = (2,0)
- lcd.write_string("Rain:" + rain)
- lcd.cursor_pos = (2,12)
- lcd.write_string("Tank:" + waterlevel)
- lcd.cursor_pos = (3,0)
- lcd.write_string("NxtWater:" + nextwater)
- #Getting data from get_data and printing it to terminal window
- def print_data():
- timenow, temp, humid, pump, rain, waterlevel, lastwater, nextwater, valve, pumpstop = get_data()
- print(" -----START-----")
- print('Temperature -- ' + (temp) + 'F')
- print('Humidity -- ' + (humid) + '%')
- print('Pump Status -- ' + (pump))
- print('Water Valve -- ' + (valve))
- print('Rain Sensor -- ' + (rain))
- print('Water Level -- ' + (waterlevel))
- print('Time Now -- ' + (datetime.now().strftime('%d/%m/%y %H:%M:%S')))
- print('Last Watered -- ' + (lastwater))
- print('Pump Stop Time -- ' + (pumpstop))
- print('Next Watering -- ' + (nextwater))
- print(" ------END------")
- #Main loop
- try:
- while True:
- lcd_display()
- print_data()
- print("Main Loop Display")
- #If the time is on a 10 save the get_data to the database and print to terminal
- if int(datetime.now().strftime('%M')) in (00,10,20,30,40,50):
- print_data()
- save_database()
- sleep(45)#45 second delay so I only get 1 reading every 10 min
- print("Saved data to database - MAIN LOOP")
- #If the rain sensor is wet we reset the nextWatering and lastWatered time
- if rain_sensor() == 'Wet':#Rain sensor is wet so we set latsWatered
- print("Its Raining")
- lastWatered = datetime.now()
- addDays = datetime.now() + relativedelta(days=waitDays)#Add waitDays to current time
- nextWatering = addDays.replace(hour=21,minute=0,second=0)#Change hour to 21:00 - 9pm
- #If this is the first time the sensor was wet sence the last time it was dry save to database
- if firstRain == 0:
- firstRain = firstRain + 1
- save_database()
- print("Saved data to database - RAIN SENSOR")
- #Set firstRain to 0 when its not raining
- else:
- firstRain = 0
- print("Its Not Raining")
- #If water level is to low we reset nextWatering to the next day
- if water_level() == 'LOW':
- print("Water Level is LOW")
- lowWater = datetime.now() + relativedelta(days=lowWaterReset)#Add lowWaterReset to current time
- nextWatering = lowWater.replace(hour=21,minute=0,second=0)#Change hour to 21:00 - 9pm
- #If the pump is off we check to see if its time to turn it on
- if pump_status() == 'OFF':
- if datetime.now() >= nextWatering:
- #Then we update the lastWatered and pumpStopTime
- pumpStopTime = datetime.now() + relativedelta(minutes=pumpRunTime)#Add pumpRunTime to current time
- print("Time to Start pump")
- pump_control('Start')
- #We also check to see if the valve is closed and return a error if the valve is SHUT
- if valve_status() == 'SHUT':
- print("Valve is CLOSED - Unable to Start")
- pump_control('ERROR')
- nextWatering = lastWatering + relativedelta(minutes=valveNotOpen)#Add valveNotOpen to current time
- #If the pump is on we check to see if it is time to turn it off and update nextWatering
- if pump_status() == 'ON':
- lastWatering = datetime.now()
- adddays = datetime.now() + relativedelta(days=waitDays)#Add waitDays to current time
- nextWatering = adddays.replace(hour=21,minute=0,second=0)#Change hour to 21:00 - 9pm
- if datetime.now() >= pumpStopTime:
- print("Time to Stop Pump")
- pump_control('Stop')
- #We also check to see if it started raining
- if rain_sensor() == 'Wet':
- print("It started raining")
- pump_control('Stop')
- #We also check to see if the water level is low
- if water_level() == 'LOW':
- print("Water Level got to LOW")
- pump_control('Stop')
- #When program ends or is interupted we cleanup the GPIO pins
- finally:
- print("Shutdown")
- database.close()
- print("Closed database")
- GPIO.cleanup()
- print("GPIO pins cleanup")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement