import time
import dht
from machine import Pin, ADC, PWM
from umqtt.simple import MQTTClient
import network
# Wi-Fi and MQTT Broker configurations
ssid = 'Wokwi-GUEST'
password = ''
mqtt_broker = 'test.mosquitto.org'
client_id = 'IrrigationIsTheFuture'
mqtt_port = 1883
mqtt_user = ''
mqtt_password = ''
# Pins
pin_dht = Pin(15)
pin_led = Pin(2, Pin.OUT)
pin_servo = Pin(4) # Servo pin
adc = ADC(Pin(34)) # Potentiometer (simulating soil moisture sensor)
# DHT22 configuration
sensor_dht = dht.DHT22(pin_dht)
# Servo configuration
servo = PWM(pin_servo, freq=50) # Frequency of 50Hz for servo control
# Wi-Fi connection
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print('Connecting to Wi-Fi...')
time.sleep(1)
print('Connected to Wi-Fi:', wlan.ifconfig())
# Function to connect to the MQTT Broker
def connect_mqtt():
try:
client = MQTTClient(client_id, mqtt_broker, mqtt_port)
# Set the callback function
client.set_callback(message_callback)
client.connect() # Connect to the MQTT broker
print('Connected to MQTT Broker')
return client
except Exception as e:
print('Failed to connect to MQTT Broker:', e)
return None
# Function to publish data
def publish(client, topic, msg):
if client: # Ensure client is not None
client.publish(topic, msg)
# Message callback for incoming messages
def message_callback(topic, msg):
print(f"Message received on topic {topic}: {msg.decode()}")
if topic == 'iot/soy/control':
if msg.decode() == 'open':
servo.duty(70) # Open valve
elif msg.decode() == 'close':
servo.duty(20) # Close valve
# Main loop
def main():
connect_wifi()
# Attempt to connect to MQTT Broker
client = connect_mqtt()
# Check if client is None before trying to subscribe
if client is None:
print("Exiting program due to MQTT connection failure.")
return
client.subscribe('iot/soy/control')
while True:
try:
client.check_msg()
# Read the potentiometer (simulating soil moisture)
moisture = adc.read()
moisture_percent = (moisture / 4095) * 100 # Conversion to percentage
# Read the DHT22 sensor
try:
sensor_dht.measure()
temp = sensor_dht.temperature()
humidity = sensor_dht.humidity()
except OSError as e:
print('Error reading DHT22:', e)
# Control the LED based on soil moisture
if moisture_percent < 30:
pin_led.value(1) # Turn on the LED if moisture is low
else:
pin_led.value(0) # Turn off the LED
# Control the Servo based on soil moisture
if moisture_percent < 30:
print("Opening the irrigation valve...")
servo.duty(70) # Turn the servo to open the valve
else:
print("Closing the irrigation valve...")
servo.duty(20) # Turn the servo to close the valve
# Publish data via MQTT
publish(client, 'iot/soy/moisture', str(moisture_percent))
publish(client, 'iot/soy/temperature', str(temp))
publish(client, 'iot/soy/humidity', str(humidity))
time.sleep(10) # Wait 10 seconds before the next reading
except Exception as e:
print('Error in main loop:', e)
time.sleep(5) # Wait before retrying
# Run the main loop
main()