The HC-SR04 has four main pins: VCC, GND, TRIG, and ECHO.
HC-SR04 pinNodeMCU connection
VCC ----VIN / suitable 5V supply
GND---GND
TRIG---D5 (GPIO14)
ECHO---D7 (GPIO13), through a voltage divider
Important voltage-safety note: The HC-SR04 is commonly powered from 5V, and its ECHO output can reach approximately 5V. ESP8266 GPIO pins are not 5V tolerant. Use a resistor voltage divider on ECHO before connecting it to D7.
For example, a 1kΞ© resistor between ECHO and D7, plus a 2kΞ© resistor between D7 and GND, reduces a 5V signal to approximately 3.3V. Connect the grounds together.
The voltage divider is essential for protecting the ESP8266. Do not connect a 5V ECHO signal directly to the GPIO pin.
Step 2: Prepare Arduino IDE- Install Arduino IDE from the official website: https://www.arduino.cc/en/software
- Open Arduino IDE.
- Install the ESP8266 board package through Boards Manager if it is not already installed.
- Select NodeMCU 1.0 (ESP-12E Module) or the matching option for your board.
- Connect the NodeMCU using a USB data cable.
- Select the correct COM port.
- Install the KiwisIoT Arduino library.
The project uses the ESP8266's GPIO pins and the KiwisIoT library to collect and transmit distance measurements.
Step 3: Create Your KiwisIoT Dashboard- Sign in to KiwisIoT.
- Create a new panel called Distance Monitoring System.
- Add a Gauge widget or numeric value widget.
- Configure the widget to receive data from Channel 1.
- Set the display label to Distance.
- Use centimeters (cm) as the unit.
- Copy the Topic ID associated with the panel.
Keep the Topic ID available for the Arduino program. Use placeholders in public code and never publish your Wi-Fi password or private credentials.
Step 4: Configure Wi-Fi and KiwisIoTThe program uses the KiwisIoT library to connect the ESP8266 to the Wi-Fi network and dashboard.
#include <KiwisIoT.h>
const char* ssid = "YOUR_WIFI_NAME";
const char* pass = "YOUR_WIFI_PASSWORD";
const char* topic = "YOUR_TOPIC_ID";
KiwisIoT kiwisiot(ssid, pass, topic);
Replace the placeholder values with your own configuration. The Topic ID must match the dashboard where you want to view the readings.
Step 5: Upload the Arduino ProgramThe following sketch follows the original project's D5 trigger, D7 echo, and Channel 1 mapping. It also includes an echo timeout to avoid waiting indefinitely when no reflection is received.
#include <KiwisIoT.h>
// Wi-Fi details
const char* ssid = "YOUR_WIFI_NAME";
const char* pass = "YOUR_WIFI_PASSWORD";
// KiwisIoT dashboard Topic ID
const char* topic = "YOUR_TOPIC_ID";
KiwisIoT kiwisiot(ssid, pass, topic);
// HC-SR04 pins
#define TRIG_PIN D5
#define ECHO_PIN D7
unsigned long duration;
float distance;
void setup()
{
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
kiwisiot.begin();
Serial.println("Distance Monitoring System Started");
}
void loop()
{
// Keep KiwisIoT communication active
kiwisiot.run();
// Generate a short trigger pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read echo duration with a 30 ms timeout
duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (duration == 0)
{
Serial.println("No echo received");
}
else
{
// Convert echo time to distance in centimeters
distance = duration * 0.0343f / 2.0f;
Serial.print("Distance: ");
Serial.print(distance, 1);
Serial.println(" cm");
// Send distance to KiwisIoT Channel 1
kiwisiot.send("1", distance);
}
delay(1000);
}
Understanding the Code- TRIG_PIN defines the trigger output on D5.
- ECHO_PIN defines the echo input on D7.
- The trigger pin sends a 10-microsecond pulse to start a measurement.
- pulseIn() measures how long the ECHO signal stays HIGH.
- distance = duration * 0.0343 / 2 converts the measured time into centimeters.
- kiwisiot.send("1", distance) sends the calculated distance to Channel 1.
- kiwisiot.run() keeps the KiwisIoT communication process active.
- delay(1000) sets an approximately one-second interval between measurements.
The code reports a missing echo instead of transmitting a misleading distance value when the sensor does not receive a valid response.
Step 6: Upload and Test the Sensor- Connect the NodeMCU to your computer.
- Verify the trigger and ECHO wiring, including the voltage divider.
- Enter your Wi-Fi credentials and KiwisIoT Topic ID.
- Compile and upload the sketch.
- Open the Serial Monitor at 115200 baud.
- Place an object in front of the sensor.
- Move the object closer to and farther from the sensor.
- Observe the distance values.
Example readings:
Distance: 15.2 cm
Distance: 25.6 cm
Distance: 40.3 cm
These are illustrative examples. Your actual readings depend on the object, sensor alignment, distance, and environmental conditions.
Step 7: Display Distance on KiwisIoTOpen your KiwisIoT panel and check the widget configured for Channel 1.
The dashboard should display the distance values transmitted by the ESP8266. Configure the widget to show centimeters so the displayed measurement is clear.
A gauge is useful for viewing the latest distance at a glance, while a chart can help you observe how the measurement changes over time if historical visualization is supported by your dashboard setup.
Step 8: Test Different DistancesTry testing the sensor with a flat object at several distances.
- Place an object close to the sensor.
- Move it farther away.
- Keep the object approximately perpendicular to the sensor.
- Compare the physical distance with the Serial Monitor.
- Check that KiwisIoT receives the corresponding values.
Avoid placing the target too close to the sensor's minimum measurement range. Soft, angled, or irregular surfaces may reflect sound poorly and produce inconsistent readings.
Step 9: Verify the Complete IoT WorkflowConfirm each stage of the project:
- The HC-SR04 generates ultrasonic pulses.
- The ECHO signal reaches the ESP8266 through a voltage divider.
- The ESP8266 calculates distance in centimeters.
- The Serial Monitor displays the measurements.
- The device connects to Wi-Fi.
- The correct Topic ID is configured.
- KiwisIoT receives the readings through Channel 1.
When the local readings and dashboard values correspond, the sensor-to-cloud data path is working.
Step 10: Final Working of the ProjectThe HC-SR04 measures the time taken for an ultrasonic pulse to return from an object. The NodeMCU ESP8266 calculates the distance and sends it to KiwisIoT over Wi-Fi.
The dashboard provides a remote view of the latest measurement, making it possible to monitor distance without relying only on the Serial Monitor.
Complete project flow:
Object β HC-SR04 β ESP8266 β Distance in cm β Wi-Fi β KiwisIoT Channel 1 β Dashboard
ApplicationsThis distance-monitoring concept can be adapted for:
- Obstacle detection prototypes
- Parking-distance indicators
- Water-tank level experiments
- Object proximity monitoring
- Robotics and navigation experiments
- Smart-home automation
- Industrial monitoring prototypes
- Educational IoT projects
For tank-level measurement, you must account for the tank geometry and sensor mounting. The ultrasonic reading measures the distance to the surface, not the volume of liquid directly.
Future ImprovementsThe project can be extended with:
- A local OLED display
- A buzzer for proximity alerts
- Configurable distance thresholds
- Historical distance charts
- Multiple ultrasonic sensors
- Automatic tank-level calculations
- Notifications when an object approaches
- Data logging for later analysis
- Filtering to reduce noisy measurements
If multiple sensors are added, trigger them sequentially to reduce interference between ultrasonic pulses.
TroubleshootingThe Sensor Always Shows No Echo- Check VCC and GND.
- Confirm the TRIG and ECHO connections.
- Verify the voltage divider wiring.
- Ensure the target is within the sensor's usable range.
- Check that the target reflects the ultrasonic signal effectively.
- Keep the sensor firmly mounted.
- Point the sensor toward a flat target.
- Avoid angled or soft surfaces.
- Try averaging several readings if the application needs smoother measurements.
- Select the correct board and COM port.
- Use a USB cable that supports data.
- Check that the ESP8266 board package is installed.
- Verify the Wi-Fi name and password.
- Confirm the Topic ID.
- Check that the dashboard widget uses Channel 1.
- Ensure kiwisiot.begin() and kiwisiot.run() are included.
- Check the Serial Monitor for valid distance readings.
1. What is the HC-SR04 sensor?
It is an ultrasonic distance sensor that estimates distance by measuring the time taken for a transmitted sound pulse to return as an echo.
2. Why is the ECHO voltage divider necessary?
The HC-SR04 ECHO output can be 5V, while ESP8266 GPIO inputs are designed for 3.3V logic. The divider reduces the voltage to protect the microcontroller.
3. Why is the distance divided by two?
The measured sound pulse travels from the sensor to the object and then back to the sensor. Dividing by two gives the one-way distance.
4. Can I monitor the distance remotely?
Yes. The ESP8266 sends the calculated value to KiwisIoT over Wi-Fi, allowing you to view it on the configured dashboard when the network and platform are available.
5. Can this project measure water level?
It can be adapted to measure the distance from a sensor mounted above the water surface. Converting that distance into a water level requires knowing the tank's geometry and reference height.
Step 11: ConclusionThis project demonstrates how an HC-SR04 ultrasonic sensor, NodeMCU ESP8266, and KiwisIoT can be combined for real-time distance monitoring.
The sensor measures echo duration, the ESP8266 calculates distance in centimeters, and KiwisIoT displays the transmitted readings on a dashboard. It is a practical starting point for learning sensor interfacing, timing measurements, Wi-Fi communication, and cloud-based visualization.
The same concept can be extended to obstacle detection, parking assistance, and tank-level experiments by adding suitable application logic and safeguards.
I recommend KiwisIoT for beginners who want to connect sensor-based hardware to an online dashboard. It provides a convenient way to visualize readings remotely without building the complete dashboard infrastructure from scratch.
Explore the KiwisIoT Projects repository:




_JnuTDtq8iW.jpeg?auto=compress%2Cformat&w=48&h=48&fit=fill&bg=ffffff)






_3u05Tpwasz.png?auto=compress%2Cformat&w=40&h=40&fit=fillmax&bg=fff&dpr=2)
Comments