from machine import Pin, Timer
import network
import time
from umqtt.robust import MQTTClient
import sys
import dht
# DHT11 Sensor on Pin 4 (GPIO4) of ESP32
sensor = dht.DHT22(Pin(4))
# Initialize LED on GPIO2
led = Pin(2, Pin.OUT)
WIFI_SSID = 'Wokwi-GUEST' # Put your own WiFi SSID
WIFI_PASSWORD = '' # Put WiFi password if no password then leave it as it is (empty)
mqtt_client_id = bytes('client_'+'12321', 'utf-8') # Just a random client ID
ADAFRUIT_IO_URL = 'io.adafruit.com' # Also known as ADAFRUIT_SERVER
ADAFRUIT_USERNAME = 'learnpracticaliot' # Put your own (Find it from your Key Icon of your account)
ADAFRUIT_IO_KEY = 'aio_HqfU40RxeZld8rxJ1QljsomDIwWY'
TEMP_FEED_ID = 'temperature'
HUM_FEED_ID = 'humidity'
ADAFRUIT_IO_FEED_LED = 'learnpracticaliot/feeds/led' # Replace with your
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(WIFI_SSID,WIFI_PASSWORD)
if not wifi.isconnected():
print('connecting...to your wifi')
timeout = 0
while (not wifi.isconnected() and timeout < 10):
print(10 - timeout)
timeout = timeout + 1
time.sleep(1)
if(wifi.isconnected()):
print('connected')
else:
print('not connected')
sys.exit()
connect_wifi() # Connecting to WiFi Router
# Callback function to handle messages from Adafruit IO
def sub_cb(topic, msg):
print(f"Received message: {msg} on topic: {topic}")
if msg == b'ON':
led.value(1)
print("LED turned ON")
elif msg == b'OFF':
led.value(0)
print("LED turned OFF")
client = MQTTClient(client_id=mqtt_client_id,
server=ADAFRUIT_IO_URL,
user=ADAFRUIT_USERNAME,
password=ADAFRUIT_IO_KEY,
ssl=False)
try:
client.connect()
client.set_callback(sub_cb) # Set the callback function
print('Connected to Adafruit IO MQTT Broker')
client.subscribe(ADAFRUIT_IO_FEED_LED) # Subscribe to the LED control feed
except Exception as e:
print('could not connect to MQTT server {}{}'.format(type(e).__name__, e))
sys.exit()
temp_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, TEMP_FEED_ID), 'utf-8') # format - learnpracticaliot/feeds/temperature
hum_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, HUM_FEED_ID), 'utf-8') # format - learnpracticaliot/feeds/humidity
def sens_data(data):
sensor.measure() # Measuring Sensor data
temp = sensor.temperature() # getting Temperature data from the measure()
hum = sensor.humidity() # getting Humidity
client.publish(temp_feed,
bytes(str(temp), 'utf-8'), # Publishing Temp feed to adafruit.io
qos=0)
client.publish(hum_feed,
bytes(str(hum), 'utf-8'), # Publishing Hum feed to adafruit.io
qos=0)
print("Temperature - ", str(temp), "Deg. Celcius")
print("Humidity - " , str(hum), "%")
print('Msg sent to Adafruit IO successfully...')
# Check for incoming MQTT messages
client.check_msg()
timer = Timer(0)
timer.init(period=5000, mode=Timer.PERIODIC, callback = sens_data)