"""
MicroPython IoT Weather and Gas Station Example for Wokwi.com
"""
import network
import time
from machine import Pin, ADC, I2C, PWM
import dht
import ujson
from umqtt.simple import MQTTClient
import ssd1306
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-gas-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
# OLED display configuration (128x64 pixels)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Initialize the DHT22 sensor and the potentiometer (MQ2)
sensor = dht.DHT22(Pin(15))
mq2_sensor = ADC(Pin(35)) # Initialize the potentiometer (MQ2) on pin 35
# Buzzer configuration
buzzer_pin = Pin(32, Pin.OUT)
buzzer = PWM(buzzer_pin)
# LED configuration
green_led = Pin(25, Pin.OUT)
red_led = Pin(27, Pin.OUT)
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
prev_weather = ""
while True:
print("Measuring weather and gas conditions... ", end="")
sensor.measure()
# Read the gas level from the potentiometer
gas_level = mq2_sensor.read() / 4095.0 * 100 # Normalize to a percentage
# Create the message payload
temperature = sensor.temperature()
humidity = sensor.humidity()
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
"gas_level": gas_level
})
# Check for threshold conditions and update OLED display and LEDs
if temperature > 28 or humidity > 48:
buzzer.freq(1000)
buzzer.duty(512) # Turn on buzzer
# Turn on red LED, turn off green LED
red_led.value(1)
green_led.value(0)
# Display warning on OLED
oled.fill(0) # Clear the OLED display
oled.text("Warning!", 0, 0)
oled.text("Over thresholds", 0, 16)
oled.text("Temp: {:.1f}C".format(temperature), 0, 32)
oled.text("Gas: {:.1f}%".format(gas_level), 0, 48)
oled.show()
print("Warning: Temperature or Humidity above threshold!")
time.sleep(1.5) # Delay for 1.5 seconds
else:
buzzer.duty(0) # Turn off buzzer
# Turn on green LED, turn off red LED
green_led.value(1)
red_led.value(0)
# Display normal conditions on OLED
oled.fill(0) # Clear the OLED display
oled.text("Condition is good", 0, 0)
oled.text("Temp: {:.1f}C".format(temperature), 0, 16)
oled.text("Hum: {:.1f}%".format(humidity), 0, 32)
oled.text("Gas: {:.1f}%".format(gas_level), 0, 48)
oled.show()
time.sleep(1.5) # Delay for 1.5 seconds
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
time.sleep(1)