#2 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/ Laptop 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.
Copyright (C) 2025, M Kamarul Zaman
https://wokwi.com/projects/429166796278789121
"""
import network
import ujson
import time
from machine import Pin, SoftI2C
from neopixel import NeoPixel
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
import ssd1306
# --- Hardware Setup ---
pixels = NeoPixel(Pin(4), 16)
pixels.fill((0, 0, 0))
pixels.write()
sensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# --- WiFi Connection ---
print("Connecting to WiFi...", end="")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
print(".", end="")
time.sleep(0.5)
print(" Connected!")
# --- MQTT Configuration ---
MQTT_CLIENT_ID = ""
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_PUB = "huda/distance"
MQTT_TOPIC_SUB = "huda/rgb"
# --- RGB Override Flag ---
rgb_override = False
# --- MQTT Callback ---
def mqtt_message(topic, msg):
global rgb_override
print("Incoming message:", msg)
try:
data = ujson.loads(msg)
if isinstance(data, list) and len(data) == 3:
r, g, b = [int(x) for x in data]
pixels.fill((r, g, b))
pixels.write()
rgb_override = True
oled.fill(0)
oled.text("RGB Value", 0, 0)
oled.text("R: {}".format(r), 0, 20)
oled.text("G: {}".format(g), 0, 35)
oled.text("B: {}".format(b), 0, 50)
oled.show()
else:
print("Invalid RGB format")
except Exception as e:
print("Error in MQTT callback:", e)
# --- Connect to MQTT ---
print("Connecting to MQTT...", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_message)
client.connect()
client.subscribe(MQTT_TOPIC_SUB)
print(" Connected!")
# --- Main Loop ---
prev_distance = ""
while True:
try:
distance = sensor.distance_cm()
print("Distance:", distance, "cm")
message = ujson.dumps(distance)
if message != prev_distance:
client.publish(MQTT_TOPIC_PUB, message)
prev_distance = message
print("Published:", message)
if not rgb_override:
if distance > 300:
pixels.fill((255, 0, 0)) # Red
else:
pixels.fill((0, 255, 0)) # Green
pixels.write()
else:
print("No distance change.")
client.check_msg()
rgb_override = False # Reset after each loop
except Exception as e:
print("Main loop error:", e)
time.sleep(1)