import network
import time
import random
from umqtt.simple import MQTTClient
from machine import Pin
import dht
# Connecting 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("\nConnected to Wifi!")
#======================================================================
# MQTT Adafruit
ADAFRUIT_IO_URL = 'io.adafruit.com'
ADAFRUIT_USERNAME = 'MusaMagwaza23'
ADAFRUIT_IO_KEY = 'aio_pVis074QcVVvkklXzpoXz0xJZkRh'
# Define your feed name
temp_feed = "temperature"
hum_feed = "humidity"
# Connect to Adafruit IO MQTT
client_id = 'ESP32'
mqtt = MQTTClient(client_id, ADAFRUIT_IO_URL, 0, ADAFRUIT_USERNAME, ADAFRUIT_IO_KEY)
# Connect to Adafruit IO MQTT
try:
mqtt.connect()
print("Connected to Adafruit IO MQTT")
except Exception as e:
print(f"Could not connect {type(e)}")
def publish(feed_name, data):
topic = f"{ADAFRUIT_USERNAME}/feeds/{feed_name}"
mqtt.publish(topic, data)
#======================================================================
def measure():
pass
sensor = dht.DHT22(Pin(15))
for i in range(5):
sensor.measure()
temp = f"{sensor.temperature()}"
hum = f"{sensor.humidity()}"
print(f"Temperature: {temp}, Humidity: {hum}")
publish(temp_feed, temp)
publish(hum_feed, hum)
time.sleep(2)