from machine import Pin, ADC, I2C
import time
import dht
import network
import ujson
from umqtt.simple import MQTTClient
time.sleep(3)
# Set up Pinout
# ADC pin (GPIO 34) -> read MQ135
# DHT sensor (GPIO 15) -> read DHT22
# Relay on GPIO 26 -> Control Relay
dht_sensor = dht.DHT22(Pin(15)) # DHT22 sensor on GPIO 15
ppm_sensor = ADC(Pin(34)) # MQ135 sensor on GPIO 34
ppm_sensor.width(ADC.WIDTH_12BIT) # 12-bit precision for ADC
led = Pin(2, Pin.OUT) # LED for indicating working status
# Toxic air quality level threshold (PPM)
toxic = 250
start_time = 0
# Set up the relay on GPIO 26
relay = Pin(26, Pin.OUT)
relay.off() # Relay is initially off
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-iot"
MQTT_BROKER = "test.mosquitto.org"
MQTT_PORT = 1883
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "iot-air-quality"
# Workig Status
def alive(t, r):
for i in range(r):
led.value(not led.value())
time.sleep(t)
# Connectivity - Connect to WiFi
def connect_wifi():
alive(.1, 4)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
print("Connecting to WiFi", end="")
if not sta_if.isconnected():
sta_if.connect('Wokwi-GUEST', '') # Use your network credentials
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.5)
print(" Connected!")
return sta_if
# MQTT Client Connection
def connect_mqtt():
alive(.05, 8)
global client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASSWORD, keepalive=60)
try:
print("Connecting to MQTT server... ", end="")
client.connect()
print("Connected!")
except Exception as e:
print("MQTT connection failed:", e)
time.sleep(2)
connect_mqtt()
# Sensor reading functions
def read_dht22():
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
except Exception as e:
print("DHT22 Sensor error:", e)
return "N/A", "N/A"
def read_mq135():
try:
ppm_value = ppm_sensor.read()
while ppm_value == 0:
print("Retrying MQ135 read...")
time.sleep(1)
ppm_value = ppm_sensor.read()
mapped_ppm = int(ppm_value / 4.095) # Convert to ppm value
if mapped_ppm > toxic:
global start_time
start_time = time.time()
return mapped_ppm
except Exception as e:
print("MQ135 Sensor error:", e)
return "N/A"
# Output devices (Relay control based on PPM)
def control_relay(ppm_value):
if ppm_value != "N/A" and ppm_value > toxic:
relay.on()
elapsed_time = time.time() - start_time
print(f"Elapsed time: {elapsed_time:.4f} seconds")
print(f"PPM exceeds {toxic}, Relay activated.")
else:
relay.off()
print(f"PPM below {toxic}, Relay deactivated.")
# Assemble the Payload for MQTT
def assemble_payload(temperature, humidity, mapped_ppm_value):
if temperature != "N/A" or humidity != "N/A" or mapped_ppm_value != "N/A":
payload = ujson.dumps({
"temperature": temperature,
"humidity": humidity,
"ppm": mapped_ppm_value
})
print("Publishing to MQTT:", payload)
print("PPM:", mapped_ppm_value, "Temp:", temperature, "Humidity:", humidity, "%")
return payload
# Main Function to Run the Program
def main():
# Connect to WiFi
connect_wifi()
# Set up MQTT client and connect
connect_mqtt()
while True:
# Read sensors
temperature, humidity = read_dht22()
mapped_ppm_value = read_mq135()
# Control relay based on air quality
control_relay(mapped_ppm_value)
# Prepare payload for MQTT and publish
payload = assemble_payload(temperature, humidity, mapped_ppm_value)
client.publish(MQTT_TOPIC, payload)
# Sleep for a while before reading again
time.sleep(1)
# Run the program
main()