import network
import time
from machine import Pin, I2C
import ujson
from umqtt.robust import MQTTClient
# Ubidots Token and Client ID
ubidotsToken = "BBUS-4e6v24O4dEhy3NeTzSnMJ5WASGcOUQ"
clientID = "dandebharath03"
# SI7021 I2C address and commands
SI7021_ADDR = 0x40
HUMIDITY_CMD = 0xF5
TEMPERATURE_CMD = 0xF3
# Initialize I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21)) # I2C(0) with pins SCL=22, SDA=21
# Connect to WiFi
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!")
# Connect to MQTT server
print("Connecting to MQTT server... ", end="")
client = MQTTClient(clientID, "industrial.api.ubidots.com", 1883, user=ubidotsToken, password=ubidotsToken)
client.connect()
print("Connected!")
# Function to read humidity from SI7021
def readHumidity():
i2c.writeto(SI7021_ADDR, bytearray([HUMIDITY_CMD])) # Send humidity measurement command
time.sleep(0.5) # Wait for measurement to complete
data = i2c.readfrom(SI7021_ADDR, 2) # Read 2 bytes of data
msb, lsb = data[0], data[1]
humidity = ((msb << 8) | lsb) * 125.0 / 65536.0 - 6.0
return humidity
# Function to read temperature from SI7021 in Celsius
def readTemperature():
i2c.writeto(SI7021_ADDR, bytearray([TEMPERATURE_CMD])) # Send temperature measurement command
time.sleep(0.5) # Wait for measurement to complete
data = i2c.readfrom(SI7021_ADDR, 2) # Read 2 bytes of data
msb, lsb = data[0], data[1]
temperature = ((msb << 8) | lsb) * 175.72 / 65536.0 - 46.85
return temperature
# Loop to send data every 1 second
prev_weather = ""
while True:
print("Measuring weather conditions... ", end="")
# Read humidity and temperature
humidity = readHumidity()
temperature = readTemperature()
# Prepare message to send
message = ujson.dumps({
"temperature": temperature,
"humidity": humidity,
})
# Only publish the message if it has changed
if message != prev_weather:
print("Updated!")
client.publish(b"/v1.6/devices/ESP32", message)
prev_weather = message
else:
print("No change")
# Sleep for 1 second before the next measurement
time.sleep(1)