from machine import Pin, ADC
from time import sleep
import dht
import network
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-bin-prototype-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-bin"
# Connect to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Change if needed
while not sta_if.isconnected():
print(".", end="")
sleep(0.1)
print(" Connected!")
# Connect to MQTT Broker
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Sensor setup
gas_sensor = ADC(Pin(36)) # GPIO36 = VP = ADC1_CH0
gas_sensor.atten(ADC.ATTN_11DB) # 0-3.6V range
led = Pin(12, Pin.OUT)
buzzer = Pin(14, Pin.OUT)
dht_sensor = dht.DHT22(Pin(4)) # GPIO4
GAS_THRESHOLD = 900 # Adjust according to your environment
prev_data = ""
while True:
gas_level = gas_sensor.read()
leak_detected = gas_level > GAS_THRESHOLD
if leak_detected:
led.on()
buzzer.on()
else:
led.off()
buzzer.off()
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print("Gas level:", gas_level)
print("Temperature: {:.1f}°C".format(temperature))
print("Humidity: {:.1f}%".format(humidity))
# Prepare the MQTT message
message = ujson.dumps({
"gas_level": gas_level,
"temperature": temperature,
"humidity": humidity,
"leak_detected": leak_detected
})
print("Publishing to MQTT...")
client.publish(MQTT_TOPIC, message)
prev_data = message
# Only send if data changed
"""if message != prev_data:
print("Publishing to MQTT...")
client.publish(MQTT_TOPIC, message)
prev_data = message
else:
print("No change in data, not publishing.")"""
except Exception as e:
print("DHT22 error:", e)
sleep(1)