import machine
import utime
from machine import Pin, SPI, ADC
from ili934xnew import ILI9341
import tt32
import glcdfont
import dht
from rotary_irq_esp import RotaryIRQ
# Pin configurations
start_button_pin = 27 # GPIO16
temp_sensor_pin = 28 # GPIO26 (analog pin for temperature sensor)
relay_pin = 5 # GPIO5 for the relay
encoder_clk_pin = 14 # GPIO14 for rotary encoder
encoder_dt_pin = 12 # GPIO12 for rotary encoder
DATA_PIN = machine.Pin(28, machine.Pin.IN, machine.Pin.PULL_UP)
sensor = dht.DHT22(DATA_PIN)
# TFT display configuration
spi = machine.SPI(1, baudrate=40000000, sck=machine.Pin(18), mosi=machine.Pin(19))
tft = ILI9341(
spi,
cs=machine.Pin(22),
dc=machine.Pin(20),
rst=machine.Pin(21),
w=320, # Adjust the width based on your display resolution
h=240, # Adjust the height based on your display resolution
r=1, # Adjust the rotation based on your needs
)
tft.set_font(tt32)
tft.fill_rectangle(0, 0, tft.width, tft.height, 0x00000000)
# Button and encoder instances
start_button = Pin(start_button_pin, machine.Pin.IN, machine.Pin.PULL_UP)
relay = Pin(relay_pin, machine.Pin.OUT)
encoder = RotaryIRQ(pin_num_clk=encoder_clk_pin, pin_num_dt=encoder_dt_pin)
# Initial setpoint temperature
setpoint_temperature = 25.0
# ON/OFF control parameters
hysteresis = 1.0 # Hysteresis for ON/OFF control
# Variable to check if the start button has been pressed at least once
start_pressed = False
def display_temperature_info(current_temperature, setpoint_temperature):
current_text = "Current Temp: {:.2f} C\nSetpoint Temp: {:.2f} C".format(current_temperature, setpoint_temperature)
tft.fill_rectangle(0, 0, tft.width, tft.height, 0x00000000)
tft.set_pos(0, 15)
tft.set_color(0xFFFF, 0x0000)
tft.print(current_text)
# Main loop
while True:
# Read temperature from sensor
sensor.measure()
current_temperature = sensor.temperature()
# Check if START button is pressed to activate the temperature controller
if not start_pressed and not start_button.value(): # Invert the logic
start_pressed = True
# Display temperature information
display_temperature_info(current_temperature, setpoint_temperature)
# If the start button has been pressed, continue updating the display
if start_pressed:
# Check if the temperature is higher than the setpoint
if current_temperature > setpoint_temperature:
# Turn on the relay (assuming HIGH activates the relay)
relay.value(1)
else:
# Turn off the relay
relay.value(0)
# Read the encoder value and update the setpoint_temperature
encoder_value = encoder.value()
setpoint_temperature += encoder_value
# Update and display temperature information
display_temperature_info(current_temperature, setpoint_temperature)
utime.sleep(1) # Adjust the delay based on your requirements