import machine
import time
import ujson
import urequests
# Define the MQTT broker parameters
MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_TOPIC = "/environment/data"
# Define the DHT22 sensor parameters
DHT22_PIN = 13
# Create a DHT22 sensor object
dht22 = machine.DHT22(DHT22_PIN)
# Connect to the MQTT broker
client = urequests.Client()
client.connect(MQTT_BROKER, MQTT_PORT)
# Publish the environment data to the MQTT topic
def publish_data(temperature, humidity):
data = {"temperature": temperature, "humidity": humidity}
json_data = ujson.dumps(data)
client.publish(MQTT_TOPIC, json_data)
# Start a loop to read the DHT22 sensor and publish the data to the MQTT broker
while True:
# Read the temperature and humidity from the DHT22 sensor
temperature, humidity = dht22.read()
# Publish the environment data to the MQTT topic
publish_data(temperature, humidity)
# Wait for 10 seconds before reading the sensor again
time.sleep(10)