import machine
import time
from umqtt.simple import MQTTClient
# Define pin numbers for sensors and actuators
TEMP_SENSOR_PIN = 0
HUMIDITY_SENSOR_PIN = 1
LIGHT_SENSOR_PIN = 2
VENTILATION_PIN = 4
IRRIGATION_PIN = 5
SHADING_PIN = 6
# MQTT Broker configuration
MQTT_BROKER = "your_broker_address"
MQTT_CLIENT_ID = "greenhouse_client"
MQTT_TOPIC_SENSOR = "greenhouse/sensor"
MQTT_TOPIC_CONTROL = "greenhouse/control"
# Function to read sensor values
def read_sensor(pin):
adc = machine.ADC(pin)
sensor_value = adc.read()
return sensor_value
# Function to control ventilation
def control_ventilation(temperature):
if temperature > 30:
# Turn on ventilation
client.publish(MQTT_TOPIC_CONTROL, "ventilation:on")
else:
# Turn off ventilation
client.publish(MQTT_TOPIC_CONTROL, "ventilation:off")
# Function to control irrigation
def control_irrigation(humidity):
if humidity < 60:
# Turn on irrigation
client.publish(MQTT_TOPIC_CONTROL, "irrigation:on")
else:
# Turn off irrigation
client.publish(MQTT_TOPIC_CONTROL, "irrigation:off")
# Function to control shading
def control_shading(light):
if light > 800:
# Close shading
client.publish(MQTT_TOPIC_CONTROL, "shading:close")
else:
# Open shading
client.publish(MQTT_TOPIC_CONTROL, "shading:open")
# Callback function for MQTT messages
def mqtt_callback(topic, msg):
print("Received message: {} on topic: {}".format(msg, topic))
# You can add logic here to act on received messages if needed
# Connect to MQTT Broker
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(MQTT_TOPIC_CONTROL)
# Main loop
while True:
# Read sensor values
temperature = read_sensor(TEMP_SENSOR_PIN)
humidity = read_sensor(HUMIDITY_SENSOR_PIN)
light = read_sensor(LIGHT_SENSOR_PIN)
# Publish sensor data to MQTT Broker
sensor_data = "Temperature: {}, Humidity: {}, Light: {}".format(temperature, humidity, light)
client.publish(MQTT_TOPIC_SENSOR, sensor_data)
# Control actuators based on sensor readings
control_ventilation(temperature)
control_irrigation(humidity)
control_shading(light)
# Wait for messages from MQTT Broker
client.check_msg()
# Delay for 5 minutes before reading sensors again
time.sleep(300)