import network
import time
from machine import Pin, ADC
import dht
import ujson
from umqtt.simple import MQTTClient
# WiFi Credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "mqtt.local"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_DATA = "wokwi-weather"
MQTT_TOPIC_CONTROL = "wokwi/control"
MQTT_TOPIC_POWER_LIMIT = "wokwi/power_limit"
# Sensors and Devices
sensor = dht.DHT22(Pin(15)) # DHT22 sensor GPIO 15
led = Pin(2, Pin.OUT) # LED GPIO 2
potentiometer = ADC(Pin(34)) # Potentiometer GPIO 34
voltage_sensor = ADC(Pin(32)) # Voltage sensor GPIO 32
relayPin = Pin(23, Pin.OUT) # Relay for bulb GPIO 23
purple_bulb = Pin(4, Pin.OUT) # Purple bulb GPIO 4
# Set ADC Resolution
potentiometer.width(ADC.WIDTH_10BIT)
potentiometer.atten(ADC.ATTN_11DB)
voltage_sensor.width(ADC.WIDTH_10BIT)
voltage_sensor.atten(ADC.ATTN_11DB)
# Default Power Limit (in Joules, assuming 1 second intervals)
power_limit = 7.0 # Default 5V
energy_consumed = 0.0 # Store total energy consumed over time
# Connect to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 10 # 10 seconds timeout
while not sta_if.isconnected() and timeout > 0:
print(".", end="")
time.sleep(1)
timeout -= 1
if sta_if.isconnected():
print(" Connected!")
else:
print(" Failed to connect! Check WiFi settings.")
exit()
# MQTT Callback Function
def mqtt_callback(topic, msg):
global power_limit, purple_bulb
print(f"Received MQTT message on {topic}: {msg}")
message = msg.decode()
# Control purple light
if message == "purple_light:on":
purple_bulb.on()
print("Purple light turned ON")
elif message == "purple_light:off":
purple_bulb.off()
print("Purple light turned OFF")
# Set Power Limit
elif topic == MQTT_TOPIC_POWER_LIMIT:
if message.startswith("set_power_limit:"):
try:
new_limit = float(message.split(":")[1])
power_limit = new_limit
print(f"Power limit set to {power_limit} Joules")
except ValueError:
print("Invalid power limit received")
# Connect to MQTT
print("Connecting to MQTT server...", end=" ")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(MQTT_TOPIC_CONTROL)
client.subscribe(MQTT_TOPIC_POWER_LIMIT)
print("Connected and Subscribed!")
prev_weather = ""
# Main Loop: Send Data & Listen for MQTT Messages
while True:
client.check_msg() # Check for control messages
# Read Sensor Data
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
pot_value = potentiometer.read()
voltage_value = voltage_sensor.read()
# Calculate Voltage and Power Consumption
voltage = (voltage_value / 1023.0) * 3.3
power_consumption = voltage * (pot_value / 1023.0) # Approximate power
# Accumulate Energy Consumption
energy_consumed += power_consumption * 1 # Energy = Power * Time (1s interval)
# Check Power Limit and Turn Off Light
if energy_consumed >= power_limit:
purple_bulb.off()
print("Power limit reached! Purple light turned OFF")
# Create JSON Payload
message = ujson.dumps({
"temp": temp,
"humidity": humidity,
"potentiometer_value": pot_value,
"voltage": voltage,
"power_consumption": power_consumption,
"energy_consumed": energy_consumed
})
# Send Data to MQTT Only if it Changed
if message != prev_weather:
print(f"Publishing to {MQTT_TOPIC_DATA}: {message}")
client.publish(MQTT_TOPIC_DATA, message)
prev_weather = message
time.sleep(2) # Delay before next reading