import network
import time
from machine import Pin, I2C
from umqtt.simple import MQTTClient
import dht
import ujson
from i2c_lcd import I2cLcd
# -------- WIFI CONFIG --------
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# -------- THINGSBOARD CONFIG --------
THINGSBOARD_SERVER = "thingsboard.cloud"
ACCESS_TOKEN = "yBa31inQF6yYOWLf0603"
# -------- SENSOR SETUP --------
sensor = dht.DHT22(Pin(15)) # you can change pin if needed
# ----- I2C LCD SETUP -----
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
# Change address if needed (0x27 or 0x3F)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# -------- CONNECT WIFI --------
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to WiFi", end="")
while not wifi.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nConnected:", wifi.ifconfig())
# -------- CONNECT MQTT --------
def connect_mqtt():
client = MQTTClient(
client_id="wokwi-device",
server=THINGSBOARD_SERVER,
user=ACCESS_TOKEN,
password=""
)
client.connect()
print("Connected to ThingsBoard")
return client
# -------- MAIN --------
connect_wifi()
client = connect_mqtt()
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
data = {
"temperature": temp,
"humidity": hum
}
lcd.clear()
lcd.putstr("Temp: {:.1f} C".format(temp))
lcd.move_to(0, 1)
lcd.putstr("Hum: {:.1f} %".format(hum))
json_data = ujson.dumps(data)
client.publish("v1/devices/me/telemetry", json_data)
print("Sent:", json_data)
except Exception as e:
print("Error:", e)
lcd.clear()
lcd.putstr("Sensor Error")
time.sleep(5)