#20 May 2025
"""
MicroPython IoT using ESP32 +HC-SR04
To view the data:
A: Mosquitto.Org
1. Ultrasonic Distance. Go to terminal : mosquitto_sub -h test.mosquitto.org -t mkz/distance
2. Download IoT MQTT Panel for your android phone
3. Plot gauge and graph for Temperature and Humidity
B: Raspberry Pi 3 Cloud IOT
1. Install Mosquitto
2. Install Node Red
3. Install Node Red Dashboard
Now click on the HC-SR04 sensor in the simulation,
change the distance, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
C: https://testclient-cloud.mqtt.cool/
To View your Mosquitto Broker
1. set tcp://test.mosquitto.org:1883
2. Set Topic to "mkz/distance"
3. Click Subscribe
4. View Messages from your Sensor from Wokwi Project
D: View Data Using Mobile Apps (Available)
1. https://play.google.com/store/search?q=iot+mqtt+panel&c=apps
2. Install Iot MQTT Panel
3. Configure Panel
4. Display data from Sensor Realtime
Copyright (C) 2025, M Kamarul Zaman
https://wokwi.com/projects/429166796278789121
"""
from machine import Pin, I2C, PWM
import ssd1306
import network
import time, utime, math
from machine import Pin
import dht
import ujson
from neopixel import NeoPixel
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
from time import sleep
pixels = NeoPixel(Pin(13), 16)
pixels.fill((0, 0, 0))
pixels.write()
# pwm
pwm = PWM(Pin(2), freq=50, duty=0)
def Servo(servo, angle):
pwm.duty(int(((angle)/180 *2 + 0.5) / 20 * 1023))
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
pixels.fill((msg[0], msg[1], msg[2]))
pixels.write()
except Exception as e:
print("Error:", e)
# MQTT Server Parameters
MQTT_CLIENT_ID = ""
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "khadijah/sensors" # change to your topic yournick/distance
# ESP32
#sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
sensor_us = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
sensor_dht22 = dht.DHT22(Pin(19))
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # enter wifi nameID and password
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_message)
client.connect()
client.subscribe("khadijah/neopixel")
print("Connected!")
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('PS4 Demo', 10, 10)
oled.show()
prev_sensors = ""
while True:
#client.wait_msg()
#Servo(2,180)
#sleep(1)
#Servo(2,0)
#sleep(1)
distance = sensor_us.distance_cm()
#print('Distance:', distance, 'cm')
sensor_dht22.measure()
temperature = sensor_dht22.temperature()
humidity = sensor_dht22.humidity()
time.sleep_ms(100)
#message = ujson.dumps(distance)
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
"distance": distance,
})
if message != prev_sensors:
print("Updated!")
print("Reporting to MQTT topic {}:{} ".format(MQTT_TOPIC, message))
oled.fill(0)
oled.text('Updated', 1, 0)
oled.text('Sensors:', 1, 10)
oled.text(str(distance), 1, 20)
oled.text('cm',70,20)
oled.text(str(temperature), 1,30)
oled.text('Celcious',50,30)
oled.text(str(humidity), 1,40)
oled.text('%Humid',50,40)
oled.show()
client.publish(MQTT_TOPIC, message)
prev_sensors = message
Servo(2,humidity)
sleep(1)
else:
print("NoChange")
#oled.fill(0)
oled.text('No change', 65, 0)
oled.show()
#Servo(2,0)
#sleep(1)
time.sleep(1)