import time
import network
from simple import MQTTClient
import gc
import dht
from machine import Pin
import ujson
# ---------------- DHT sensor setup ----------------
DHT_PIN = 26
sensor = dht.DHT22(Pin(DHT_PIN))
# sensor = dht.DHT11(Pin(DHT_PIN))
SSID = "Interfy"
PASSWORD = "!ParthIra@135#"
BROKER = "broker.emqx.io"
PORT = 1883
CLIENT_ID = "pico_subscriber_1"
# Topic to subscribe to
TOPIC1 = b"/tripti123/temperature" # bytes required (prefix b"")
TOPIC2 = b"/tripti123/humidity"
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to Wi-Fi...")
wlan.connect(SSID, PASSWORD)
timeout = 15
while not wlan.isconnected() and timeout > 0:
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print("✅ Wi-Fi connected:", wlan.ifconfig())
else:
raise RuntimeError("❌ Wi-Fi failed")
def on_message(topic, msg):
print("📩 Received")
print(" Topic:", topic)
print(" Msg :", msg)
def mqtt_connect():
client = MQTTClient(CLIENT_ID, BROKER, port=1883, keepalive=60)
client.connect()
print("✅ MQTT connected to", BROKER)
return client
# -------- Main --------
wifi_connect()
client = mqtt_connect()
gc.collect()
while True:
try:
sensor.measure() # triggers a new reading
t = float(sensor.temperature())
h = float(sensor.humidity()) # %
temp = "{:.1f}".format(t)
hum = "{:.1f}".format(h)
payload = {
"temp": temp,
"hum": hum
}
# ✅ Convert dict → JSON string
json_payload = ujson.dumps(payload)
client.publish(TOPIC1, json_payload)
print("Published")
gc.collect()
except Exception as e:
# If reading fails (common with DHT), show error but keep looping
print("Error details", e)
client.connect()
t = None
h = None
time.sleep(5)