#25 April 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 time
from machine import Pin, SoftI2C
import ujson
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
from time import sleep
import ssd1306
# MQTT Server Parameters
MQTT_CLIENT_ID = ""
MQTT_BROKER = "broker.mqtt.cool"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "chai/distance"
# Initialize HC-SR04
sensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
# Initialize OLED display (SCL=22, SDA=21)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Function to show distance on OLED
def show_on_oled(distance):
oled.fill(0) # Clear screen
oled.text("Distance:", 0, 0)
oled.text("{:.2f} cm".format(distance), 0, 20)
oled.show()
# Connect to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Change this to your SSID/password
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Connect to MQTT
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
prev_distance = ""
while True:
distance = sensor.distance_cm()
print('Distance:', distance, 'cm')
show_on_oled(distance) # Display on OLED
sleep(1)
message = ujson.dumps(distance)
if message != prev_distance:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_distance = message
else:
print("No change")
time.sleep(1)