Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import logging
- import datetime
- import board
- import adafruit_dht
- import gpiozero as gpio
- from importlib import reload
- from tkinter import *
- # Function to make time stamps for logging.
- def timestamp():
- return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:')
- # Set logging Level: logging.INFO, logging.WARNING, logging.ERROR, logging.DEBUG
- logging.basicConfig(filename='thermostat.log',level=logging.INFO)
- logging.info(timestamp() + "Initializing sensor and relays...")
- # Initialize the dht device, with data pin connected to:
- dhtDevice = adafruit_dht.DHT22(board.D17)
- # Set GPIO pins for relays, set to OPEN state (0), use LED function to toggle on and off
- relay1 = gpio.LED(18, initial_value=0)
- relay2 = gpio.LED(23, initial_value=0)
- logging.info(timestamp() + "waiting 5 seconds to save relay wear...")
- time.sleep(5.0)
- # Cause i don't know how else to trigger it... :)
- while True:
- # Would love to make a function; except when i do it complains about "temperature_f is not defined" even when i set it as a global variable... the error comes from the guiTemp and guiTempText within the tkinter GUI code.
- try:
- # Get data from dht sensor
- temperature = dhtDevice.temperature
- temperature_f = round(temperature * (9 / 5) + 32)
- except RuntimeError as error:
- # Errors happen fairly often, DHT's are hard to read, just log and keep going
- logging.error(timestamp() + error.args[0])
- # Set default values to avoid NPE errors.
- currentMode = "NULL"
- setTemp = 68
- # Thermostat function
- def thermostat():
- global currentMode
- global temperature
- global temperature_f
- guiTemp.config(text=temperature_f)
- logging.info(timestamp() + currentMode)
- logging.info(timestamp() + "Set temp set to: " + str(setTemp))
- # Heating logic
- if currentMode == "Heat":
- if relay2.value == 1:
- relay2.off()
- logging.debug(timestamp() + "Relay2 (cool) enabled; disabling")
- if temperature_f < setTemp:
- logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
- logging.info(timestamp() + "Temperature less than desired temp: Heating")
- if relay1.value == 0:
- relay1.on()
- else:
- logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
- logging.info(timestamp() + "Not running")
- if relay1.value == 1:
- relay1.off()
- logging.debug(timestamp() + "disabling relay1 (heat)")
- # Cooling logic
- if currentMode == "Cool":
- if relay1.value == 1:
- relay1.off()
- logging.debug(timestamp() + "Relay1 (heat) enabled; disabling")
- if temperature_f > setTemp:
- logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
- loggin.info(timestamp() + "Temperature greater than desired temp: Cooling")
- if relay2.value == 0:
- relay2.on()
- else:
- logging.debug(timestamp() + "Temp: {:.1f}".format(temperature_f))
- logging.info(timestamp() + "Not running")
- if relay2.value == 1:
- relay2.off()
- logging.debug(timestamp() + "disabling relay2 (cool)")
- # Repeat of above try function to get GUI to update; cause i'm lazy.
- try:
- # Print the values to the serial port
- temperature = dhtDevice.temperature
- temperature_f = round(temperature * (9 / 5) + 32)
- except RuntimeError as error:
- # Errors happen fairly often, DHT's are hard to read, just keep going
- logging.error(timestamp() + error.args[0])
- main.after(3000,thermostat) # Runs the loop every 3 seconds within the function.
- main = Tk() # Main tkinter function.
- main.title("Thermostat")
- main.geometry("800x600") # Sets window resolution
- main.configure(bg="black", cursor="none") # Sets background color of the window to black and disables the Mouse Cursor.
- main.overrideredirect(True) # Makes fullscreen
- guiTempText = Label(main, text="Current Temperature: ", font=(None, 25), fg="white", bg="black")
- guiTemp = Label(main, text=temperature_f, font=(None, 30), fg="white", bg="black")
- guiTemp.config(text=temperature_f)
- guiTempText.place(relx = 0.5, rely= 0.10, anchor = CENTER)
- guiTemp.place(relx = 0.5, rely= 0.20, anchor = CENTER)
- setTempLabel = Label(main, font=(None, 20), text=setTemp, fg="white", bg="black")
- setTempLabel.place(relx = 0.5, rely= 0.40, anchor = CENTER)
- # Create setTemp adjustment buttons and place them in the GUI
- def tempPlusButtonClick():
- global setTemp
- setTemp = setTemp + 1
- setTempLabel.config(text=setTemp)
- print(setTemp)
- return
- def tempMinusButtonClick():
- global setTemp
- setTemp = setTemp - 1
- setTempLabel.config(text=setTemp)
- logging.debug(timestamp() + setTemp)
- return
- plusButton = Button(main, text="+", fg="white", bg="black", padx=20, pady=20, command=tempPlusButtonClick)
- plusButton.place(relx = 0.4, rely= 0.40, anchor = CENTER)
- minusButton = Button(main, text="-", fg="white", bg="black", padx=20, pady=20, command=tempMinusButtonClick)
- minusButton.place(relx = 0.6, rely= 0.40, anchor = CENTER)
- # Create currentMode set buttons and places them in the GUI
- def heatButtonClick():
- global currentMode
- currentMode = "Heat"
- currentModeLabel.config(text="Current Mode: " + currentMode)
- logging.info(timestamp() + "Mode set to Heat")
- return
- def coolButtonClick():
- global currentMode
- currentMode = "Cool"
- currentModeLabel.config(text="Current Mode: " + currentMode)
- logging.info(timestamp() + "Mode set to Cool")
- return
- currentModeLabel = Label(main, text="Current Mode: " + currentMode, font=(None, 20), fg="white", bg="black")
- currentModeLabel.place(relx = 0.5, rely= 0.55, anchor = CENTER)
- heatButton = Button(main, text="Heat", padx=30, pady=30, bg="red", command=heatButtonClick)
- heatButton.place(relx = 0.4, rely= 0.70, anchor = CENTER)
- coolButton = Button(main, text="Cool", padx=30, pady=30, bg="blue", command=coolButtonClick)
- coolButton.place(relx = 0.6, rely= 0.70, anchor = CENTER)
- # Run a loop every 3 seconds after the thermostat function to update the GUI
- main.after(3000,thermostat)
- # Has to be here otherwise the program doesn't run.
- main.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement