import network
import ubinascii
from umqtt.simple import MQTTClient
import ssd1306
from machine import Pin, I2C, PWM
import machine
from time import sleep
import dht
import BlynkLib
# Declare connections for DHT22 sensor
dht_sensor = dht.DHT22(Pin(14)) # Change pin number accordingly
# OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Buzzer
buzzer = PWM(Pin(17), freq=1703, duty=0)
# LED setup
green_led = Pin(15, Pin.OUT)
red_led = Pin(2, Pin.OUT)
# Thresholds
TEMP_THRESHOLD = 36.0 # Temperature threshold in degrees Celsius
HUMIDITY_THRESHOLD = 55.0 # Humidity threshold in percentage
# WiFi settings
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
# MQTT settings for HiveMQ broker
MQTT_CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode()
MQTT_BROKER = "test.mosquitto.org"
MQTT_PORT = 1883 # The default port for MQTT
MQTT_USER = "" # Leave empty if no authentication is needed
MQTT_PASSWORD = "" # Leave empty if no authentication is needed
MQTT_TOPIC_TEMPT = "farm/temperature"
MQTT_TOPIC_HUMIDITY = "farm/humidity"
MQTT_TOPIC_CONTROL = "farm/control"
# Blynk settings
BLYNK_TEMPLATE_ID = "TMPL6w4zzBfuy"
BLYNK_TEMPLATE_NAME = "Quickstart Template"
BLYNK_AUTH = "K_Z5s9JBmy42Jy3hBcGrWNa1jM5br1OG"
# Flags to keep track of manual control
manual_control_red = False
manual_control_green = False
# Connect to WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
sleep(1)
print("Connected to WiFi")
# MQTT callback function
def sub_callback(topic, msg):
print((topic, msg))
if msg == b'fan_on':
fan.on()
print("Fan turned on")
elif msg == b'fan_off':
fan.off()
print("Fan turned off")
elif msg == b'pump_on':
pump.on()
print("Pump turned on")
elif msg == b'pump_off':
pump.off()
print("Pump turned off")
# Connect to MQTT
def connect_mqtt():
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_callback)
client.connect()
client.subscribe(MQTT_TOPIC_CONTROL)
print(f"Connected to {MQTT_BROKER} and subscribed to {MQTT_TOPIC_CONTROL}")
return client
except Exception as e:
print(f"Failed to connect to MQTT broker: {e}")
return None
# Function to get temperature and humidity
def get_temperature_humidity():
try:
dht_sensor.measure()
return dht_sensor.temperature(), dht_sensor.humidity()
except Exception as e:
print(f"Error getting temperature and humidity: {e}")
return None, None
# Main loop
def main():
global manual_control_red, manual_control_green
connect_wifi()
client = connect_mqtt()
if client is None:
print("Failed to connect to MQTT broker. Exiting.")
return
blynk = BlynkLib.Blynk(BLYNK_AUTH) # Initialize Blynk
# Define Blynk virtual pin callbacks
@blynk.on("V4")
def v4_write_handler(value):
global manual_control_red
manual_control_red = True
if int(value[0]) == 1:
red_led.on()
print("Red LED turned on via Blynk")
else:
red_led.off()
manual_control_red = False
print("Red LED turned off via Blynk")
@blynk.on("V3")
def v3_write_handler(value):
global manual_control_green
manual_control_green = True
if int(value[0]) == 1:
green_led.on()
print("Green LED turned on via Blynk")
else:
green_led.off()
manual_control_green = False
print("Green LED turned off via Blynk")
while True:
blynk.run() # Process Blynk events
temperature, humidity = get_temperature_humidity()
if temperature is not None and humidity is not None:
temp_data = f"Temperature: {temperature}C"
hum_data = f"Humidity: {humidity}%"
# Print to serial monitor
print(temp_data)
print(hum_data)
# Publish to MQTT
try:
client.publish(MQTT_TOPIC_TEMPT, str(temperature))
client.publish(MQTT_TOPIC_HUMIDITY, str(humidity))
except Exception as e:
print(f"Failed to publish to MQTT: {e}")
# Display on OLED
oled.fill(0) # Clear the display
oled.text("Temp: {}C".format(temperature), 0, 0, 1)
oled.text("Humidity: {}%".format(humidity), 0, 20, 1)
oled.show()
# Send data to Blynk
try:
blynk.virtual_write(1, temperature) # Virtual pin V1 for temperature
blynk.virtual_write(2, humidity) # Virtual pin V2 for humidity
except Exception as e:
print(f"Failed to send data to Blynk: {e}")
# Check thresholds and keep buzzer on if either exceeds
if not manual_control_red and not manual_control_green:
if temperature > TEMP_THRESHOLD or humidity > HUMIDITY_THRESHOLD:
red_led.on()
green_led.on()
buzzer.duty(400) # Buzzer ON
print("Buzzer turned on due to threshold exceedance")
else:
red_led.off()
green_led.off()
buzzer.duty(0) # Buzzer OFF
print("Buzzer turned off as values are within threshold")
# Check MQTT messages
try:
client.check_msg() # check for control messages
except Exception as e:
print(f"Failed to check MQTT messages: {e}")
sleep(10)
if __name__ == "__main__":
main()