Production-grade IoT project combining ESP32, ultrasonic sensing, and modern web technologies for real-time distance monitoring accessible from any device.
⚡ Perfect for IoT learning, smart home projects, and proximity detection systems
Features • Demo • Quick Start • API • Troubleshooting
- 🌟 Project Overview
- ✨ Key Features
- 🎬 Demo & Preview
- 📦 Hardware Requirements
- 🔌 Circuit Connections
- 💻 Software Setup
- 🚀 Quick Start Guide
- ⚙️ Configuration
- 🧠 System Architecture
- 📡 API Reference
- 🎨 Customization
- 🐛 Troubleshooting
- 📊 Technical Specifications
- 🤝 Contributing
- 📞 Connect
ESP32 Distance Monitor is a comprehensive IoT project that uses an ultrasonic sensor to measure distances and displays real-time data through a sleek, responsive web interface accessible from any device on your network.
|
For Learning:
|
For Building:
|
| Category | Features |
|---|---|
| 🖥️ Web Interface |
✅ Real-time distance display (200ms updates) ✅ Visual status indicators (Safe/Warning/Alert) ✅ Interactive range bar visualization ✅ Connection status monitoring ✅ Fully responsive (desktop/tablet/mobile) ✅ Smooth animations and transitions |
| 🔌 Hardware |
✅ HC-SR04 ultrasonic sensor support ✅ Configurable detection zone (1-100cm) ✅ High-precision measurements ✅ Flexible GPIO pin configuration ✅ Error filtering and validation ✅ 20 readings per second |
| 🌐 Network |
✅ WiFi connectivity with auto-reconnect ✅ RESTful API with JSON responses ✅ CORS-friendly for external apps ✅ Low latency real-time updates ✅ Multi-device access ✅ Easy network configuration |
| 💻 Development |
✅ Clean, well-documented code ✅ Modular architecture ✅ Arduino IDE compatible ✅ Easy customization ✅ Professional error handling ✅ Debug-friendly design |
|
✅ Safe Zone |
🟡 Yellow background
|
🚨 Alert Zone 🔴 Red background
|
┌────────────────────────────────────────────────────┐
│ ESP32 Distance Monitor │
│ Real-Time Web Interface │
│ │
│ ┌──────────────────────────────────────────┐ │
│ │ ✓ All Clear - Safe Zone │ │
│ └──────────────────────────────────────────┘ │
│ │
│ 25.3 cm │
│ ━━━━━━━━━━━━━━ │
│ │
│ ├────────────●───────────────────────────┤ │
│ 0cm 25cm 100cm │
│ │
│ Connected | Last update: 0.2s ago │
└────────────────────────────────────────────────────┘
┌─────────────┐ ┌──────────────┐ ┌────────────────┐
│ HC-SR04 │ GPIO │ ESP32 │ WiFi │ Web Browser │
│ Ultrasonic │ ──────> │ Web Server │ ──────> │ (Any Device) │
│ Sensor │ │ Port 80 │ │ Dashboard │
└─────────────┘ └──────────────┘ └────────────────┘
│ │ │
│ Ultrasonic pulses │ Distance calculation │ Live updates
│ 40 kHz signal │ JSON API response │ 200ms refresh
│ Echo detection │ Web server handling │ Visual feedback
└────────────────────────┴──────────────────────────┘
Continuous real-time monitoring loop
|
5V Power Supply For standalone operation |
Project Enclosure 3D printed or commercial case |
LED Indicators Additional visual feedback |
OLED Display Standalone local readout |
| Item | Approximate Cost |
|---|---|
| ESP32 Board | $5-15 |
| HC-SR04 Sensor | $2-5 |
| Jumper Wires & Breadboard | $3-8 |
| USB Cable | $2-5 |
| Total | $12-33 |
|
Standard Connection Diagram: |
Pin Configuration Table:
*Suggested colors for easy identification |
Click to read about 5V tolerance and safety
HC-SR04 ECHO Pin Output:
- The HC-SR04 ECHO pin outputs 5V logic levels
- ESP32 GPIO pins are officially rated for 3.3V logic
- However, GPIO 18 and 19 are generally 5V tolerant
Safety Options:
-
Direct Connection (Most Common)
- Connect ECHO directly to GPIO 19
- Works in 99% of cases with no issues
- Convenient for prototyping
-
Voltage Divider (Safest)
ECHO ──┬── 1kΩ ──┬── GPIO 19 │ │ └── 2kΩ ──┴── GND- Reduces 5V to 3.3V safely
- Recommended for long-term/production use
-
Logic Level Shifter
- Use a bi-directional level shifter module
- Professional solution
- Adds extra components
Our Recommendation: Direct connection works reliably for hobby projects and learning. Use voltage divider for permanent installations.
Want to use different GPIO pins? Simply modify these lines in the code:
const int trigPin = 18; // Change to your preferred TRIG pin
const int echoPin = 19; // Change to your preferred ECHO pinRecommended GPIO Pins for ESP32:
- Avoid: GPIO 0, 2, 12, 15 (used for boot strapping)
- Safe to use: GPIO 4, 5, 13, 14, 16, 17, 18, 19, 21, 22, 23, 25-27, 32-33
|
Arduino IDE Version 1.8.x or 2.x Download |
ESP32 Board Support By Espressif Systems Version 2.x or later |
USB Drivers CP210x or CH340 Board dependent |
Built-in Libraries (No installation needed):
WiFi.h- ESP32 WiFi connectivityWebServer.h- HTTP web server functionality
All dependencies come with the ESP32 board package! 🎉
Click for detailed installation instructions
1. Download Arduino IDE:
- Visit arduino.cc/software
- Download appropriate version for your OS
- Install with default settings
2. Add ESP32 Board Support:
- Open Arduino IDE
- Go to File → Preferences
- In "Additional Board Manager URLs", add:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json - Click OK
- Go to Tools → Board → Boards Manager
- Search for "esp32"
- Install "esp32 by Espressif Systems" (latest version)
- Wait for installation to complete
3. Install USB Drivers (if needed):
- CP210x: Silicon Labs
- CH340: Manufacturer site
- Identify your chip: Look at the small chip near USB port on ESP32
-
Clone or Download this repository:
git clone https://github.com/your-username/esp32-distance-monitor.git cd esp32-distance-monitor -
Open
esp32_webserver.inoin Arduino IDE -
Configure WiFi Credentials (lines 6-7):
const char* ssid = "Your_WiFi_Name"; // Replace with your WiFi name const char* password = "Your_WiFi_Password"; // Replace with your WiFi password
-
Verify Pin Configuration (lines 10-11):
const int trigPin = 18; // HC-SR04 TRIG pin const int echoPin = 19; // HC-SR04 ECHO pin
-
Optional: Adjust Detection Range (lines 14-15):
const float MIN_DISTANCE = 1.0; // Minimum detection (cm) const float MAX_DISTANCE = 100.0; // Maximum detection (cm)
|
Select Board:
Select Port:
|
Upload Settings:
Upload Process:
|
- Open Serial Monitor:
Tools→Serial Monitor(orCtrl+Shift+M) - Set baud rate to 115200
- Press RST button on ESP32
Expected Output:
Connecting to WiFi: YourNetworkName
.....
WiFi connected successfully!
IP Address: 192.168.1.100
Web server started
Distance: 25.3 cm
Distance: 23.7 cm
Distance: 21.4 cm
- Note the IP address from Serial Monitor (e.g.,
192.168.1.100) - Open any web browser on your phone/computer
- Navigate to:
http://YOUR_ESP32_IP- Example:
http://192.168.1.100
- Example:
- Success! You should see the distance monitor dashboard 🎉
Can't access? Click for tips
- ✅ Ensure device is on the same WiFi network
- ✅ Try accessing from multiple devices (phone, laptop)
- ✅ Check if ESP32 is still running (LED should be on)
- ✅ Verify IP address in Serial Monitor
- ✅ Try http://192.168.x.x (with exact IP)
- ✅ Disable VPN if active
- ✅ Check router firewall settings
|
🌐 WiFi Configuration // Network credentials
const char* ssid = "YourWiFiName";
const char* password = "YourPassword";Tips:
|
📡 Sensor Pin Assignment // GPIO pin configuration
const int trigPin = 18; // Trigger output
const int echoPin = 19; // Echo inputBest Practices:
|
📏 Detection Range Settings
// Distance thresholds (in centimeters)
const float MIN_DISTANCE = 1.0; // Minimum measurable distance
const float MAX_DISTANCE = 100.0; // Maximum detection range
// Example: Detect objects 10-50cm away
const float MIN_DISTANCE = 10.0;
const float MAX_DISTANCE = 50.0;Considerations:
- HC-SR04 reliable range: 2-400 cm
- Shorter ranges = more accurate
- Longer ranges may have errors on small objects
⏱️ Measurement Timing
Located in loop() function:
// Current: 50ms between measurements = 20 readings/second
delay(50);
// Options:
delay(20); // 50 Hz - Very fast, may cause instability
delay(50); // 20 Hz - Balanced (RECOMMENDED)
delay(100); // 10 Hz - Stable, slower updates
delay(200); // 5 Hz - Very stable, best for averagingGuidelines:
- Faster = more responsive, more CPU usage
- Slower = more stable, better for filtering
- Match web update rate for best experience
🌐 Web Update Rate
In the HTML JavaScript section:
// Update display every 200ms
setInterval(updateDisplay, 200);
// Options:
setInterval(updateDisplay, 100); // Faster updates, more traffic
setInterval(updateDisplay, 200); // Balanced (RECOMMENDED)
setInterval(updateDisplay, 500); // Slower, reduced network load
setInterval(updateDisplay, 1000); // 1 second updates, minimal trafficBest Practice:
- Web update rate ≥ measurement interval
- Consider network bandwidth
- Mobile devices may benefit from slower rates
🎨 Custom Thresholds (Web UI)
Modify JavaScript in HTML section:
// Current alert zones
if (distance > 0 && distance < 10) {
status = "🚨 Too Close!";
statusClass = "alert";
} else if (distance >= 10 && distance < 40) {
status = "⚠️ Warning Zone";
statusClass = "warning";
} else if (distance >= 40) {
status = "✓ All Clear";
statusClass = "safe";
}
// Example: Custom zones for parking sensor
if (distance > 0 && distance < 20) {
status = "🛑 STOP!";
statusClass = "alert";
} else if (distance >= 20 && distance < 50) {
status = "⚠️ Slow Down";
statusClass = "warning";
} else if (distance >= 50) {
status = "✅ Safe Distance";
statusClass = "safe";
}┌──────────────────────────────────────────────────────────────────┐
│ ESP32 System Architecture │
│ │
│ ┌──────────────┐ ┌─────────────┐ ┌─────────────────┐ │
│ │ HC-SR04 │ GPIO │ ESP32 │ WiFi │ Web Browser │ │
│ │ Ultrasonic │─────▶│ Core │◀────▶│ (Client) │ │
│ │ Sensor │ │ │ │ │ │
│ └──────────────┘ └──────┬──────┘ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Web Server │ │
│ │ (Port 80) │ │
│ └──────┬──────┘ │
│ │ │
│ ┌──────────┴──────────┐ │
│ │ │ │
│ ┌─────▼──────┐ ┌────▼─────┐ │
│ │ / │ │ /data │ │
│ │ (HTML UI) │ │ (JSON) │ │
│ └────────────┘ └──────────┘ │
└──────────────────────────────────────────────────────────────────┘
|
Physical Process:
|
Mathematical Foundation: Why divide by 2?
|
Sensor Reading → Distance Calc → Web Server → API Response → Browser → UI Update
(50ms) (instant) (minimal) (10-50ms) (instant) (smooth)
└──────────────────────────────────────────────────────────────┘
Total latency: < 100ms
┌─────────────┐ ┌──────────────┐
│ Browser │ │ ESP32 │
│ (Client) │ │ Web Server │
└──────┬──────┘ └──────┬───────┘
│ │
│ GET / │
├─────────────────────────────────▶│
│ │
│ Response: HTML + CSS + JS │
│◀─────────────────────────────────┤
│ │
│ GET /data (every 200ms) │
├─────────────────────────────────▶│
│ │
│ Response: {"distance": 25.3} │
│◀─────────────────────────────────┤
│ │
│ Update UI with new value │
│ │
│ GET /data (continuous polling) │
├─────────────────────────────────▶│
│ │
Description: Returns the main HTML interface with embedded CSS and JavaScript
Response Type: text/html
Status Codes:
200 OK- Page served successfully
Example:
curl http://192.168.1.100/Description: Returns current sensor data in JSON format
Response Type: application/json
Response Format:
{
"distance": 25.3,
"trigger": false
}Field Descriptions:
| Field | Type | Range | Description |
|---|---|---|---|
distance |
float | 0 - 400 | Current distance in centimeters |
trigger |
boolean | true/false | Alert status (resets after read) |
Special Values:
distance: 0- Out of range or measurement errordistance: -1- Sensor timeout (rare)trigger: true- Object detected in alert zone (1-100cm)trigger: false- No alert or already acknowledged
Status Codes:
200 OK- Data retrieved successfully500 Internal Server Error- Sensor malfunction
JavaScript (Browser/Node.js)
// Simple fetch
async function getDistance() {
try {
const response = await fetch('http://192.168.1.100/data');
const data = await response.json();
console.log(`Distance: ${data.distance} cm`);
console.log(`Alert: ${data.trigger}`);
return data;
} catch (error) {
console.error('Connection error:', error);
}
}
// Continuous monitoring
setInterval(async () => {
const data = await getDistance();
if (data.trigger) {
alert('Object detected!');
}
}, 200);Python (Requests)
import requests
import time
ESP32_IP = "http://192.168.1.100"
def get_distance():
try:
response = requests.get(f"{ESP32_IP}/data", timeout=1)
data = response.json()
print(f"Distance: {data['distance']} cm")
print(f"Alert: {data['trigger']}")
return data
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
# Continuous monitoring
while True:
data = get_distance()
if data and data['trigger']:
print("⚠️ ALERT: Object detected!")
time.sleep(0.2)Arduino/ESP32 (HTTPClient)
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
void readDistance() {
HTTPClient http;
http.begin("http://192.168.1.100/data");
int httpCode = http.GET();
if (httpCode == 200) {
String payload = http.getString();
StaticJsonDocument<200> doc;
deserializeJson(doc, payload);
float distance = doc["distance"];
bool trigger = doc["trigger"];
Serial.printf("Distance: %.1f cm, Alert: %s\n",
distance, trigger ? "YES" : "NO");
}
http.end();
}Command Line (curl)
# Simple request
curl http://192.168.1.100/data
# Pretty print JSON
curl -s http://192.168.1.100/data | python -m json.tool
# Continuous monitoring (Linux/Mac)
watch -n 0.2 'curl -s http://192.168.1.100/data | python -m json.tool'
# Save to file with timestamp
while true; do
echo "$(date +%T): $(curl -s http://192.168.1.100/data)" >> distance_log.txt
sleep 0.2
done|
Email Alerts: #include <ESP_Mail_Client.h>
void sendAlert(float distance) {
SMTPSession smtp;
ESP_Mail_Session session;
// Configure SMTP settings
// Send email when trigger detected
}IFTTT Integration: #include <HTTPClient.h>
void triggerIFTTT() {
HTTPClient http;
String url = "https://maker.ifttt.com/trigger/";
url += "distance_alert/with/key/YOUR_KEY";
http.begin(url);
http.GET();
} |
SD Card Storage: #include <SD.h>
void logDistance(float distance) {
File dataFile = SD.open("log.csv", FILE_APPEND);
if (dataFile) {
dataFile.print(millis());
dataFile.print(",");
dataFile.println(distance);
dataFile.close();
}
}Cloud Upload: // ThingSpeak, Firebase, or AWS IoT
#include <ThingSpeak.h>
void uploadToCloud(float distance) {
ThingSpeak.setField(1, distance);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
} |
🖥️ Add Local Display (OLED)
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
// ... existing setup code ...
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
}
void loop() {
float distance = measureDistance(trigPin, echoPin);
// Display on OLED
display.clearDisplay();
display.setCursor(0, 0);
display.print("Distance:");
display.setCursor(0, 25);
display.print(distance, 1);
display.print(" cm");
display.display();
// ... existing loop code ...
}🔊 Add Audio Feedback
// Buzzer on GPIO 25
#define BUZZER_PIN 25
void setup() {
// ... existing setup code ...
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
float distance = measureDistance(trigPin, echoPin);
// Beep faster as object gets closer
if (distance > 0 && distance < 30) {
int beepDelay = map(distance, 1, 30, 50, 500);
digitalWrite(BUZZER_PIN, HIGH);
delay(50);
digitalWrite(BUZZER_PIN, LOW);
delay(beepDelay);
}
// ... existing loop code ...
}🤖 Multiple Sensors
// Define multiple sensors
const int trig1 = 18, echo1 = 19; // Front sensor
const int trig2 = 22, echo2 = 23; // Rear sensor
const int trig3 = 26, echo3 = 27; // Side sensor
float distances[3];
void loop() {
distances[0] = measureDistance(trig1, echo1);
distances[1] = measureDistance(trig2, echo2);
distances[2] = measureDistance(trig3, echo3);
// Update web server to return array
// Modify HTML to display all three readings
}❌ ESP32 Won't Connect to WiFi
Symptoms:
- Serial Monitor shows repeated dots:
Connecting to WiFi: YourNetwork..... - Eventually shows "FAILED" or never connects
- Web interface inaccessible
Solutions:
-
Check WiFi Credentials
// Verify these match EXACTLY (case-sensitive) const char* ssid = "YourWiFiName"; const char* password = "YourPassword";
- Remove any extra spaces
- Check for special characters
- Ensure quotes are correct
-
Verify 2.4GHz Network
- ESP32 only supports 2.4GHz WiFi
- Check router settings
- Some routers separate 2.4GHz and 5GHz bands
- Connect to 2.4GHz specifically
-
Signal Strength
- Move ESP32 closer to router
- Check for physical obstacles
- Avoid metal enclosures during testing
-
Router Settings
- Check MAC address filtering (disable or add ESP32)
- Verify DHCP is enabled
- Check if network is WPA2 (not WEP or WPA3 only)
- Some enterprise networks won't work
-
Reset ESP32
- Hold BOOT button while pressing RST
- Release RST, then release BOOT
- Re-upload sketch
-
Debug WiFi Status Add this to code:
Serial.println(WiFi.status()); // Status codes: // 0 = WL_IDLE_STATUS // 1 = WL_NO_SSID_AVAIL (network not found) // 3 = WL_CONNECTED // 4 = WL_CONNECT_FAILED (wrong password)
📏 Distance Always Shows 0 or Invalid
Symptoms:
- Web interface shows "0 cm" or "--"
- Serial Monitor shows consistent 0 readings
- No valid measurements
Solutions:
-
Verify Wiring
HC-SR04 ESP32 VCC → 5V (NOT 3.3V!) TRIG → GPIO 18 ECHO → GPIO 19 GND → GND- Double-check each connection
- Ensure wires are firmly inserted
- Look for loose breadboard connections
-
Check Power Supply
- Measure VCC with multimeter: should be 4.8-5.2V
- Try different USB cable (some are power-only)
- Try different USB port or power adapter
- Ensure ESP32 5V pin is actually outputting 5V
-
Test Sensor
- Ensure clear line of sight (no obstructions)
- Hold flat object 20cm in front
- Test on Arduino UNO if available
- Sensor may be damaged if dropped
-
Pin Configuration
// Verify these match your wiring const int trigPin = 18; const int echoPin = 19; // Try different pins if issues persist const int trigPin = 22; const int echoPin = 23;
-
Measurement Environment
- Avoid soft surfaces (foam, fabric) - they absorb sound
- Avoid angled surfaces - causes reflections away
- Test with flat, hard surface (cardboard, wall)
- Ensure sensor is horizontal and stable
-
Add Debug Output
unsigned long duration = pulseIn(echoPin, HIGH, 30000); Serial.print("Duration: "); Serial.println(duration); // Should be 200-23000 for valid readings
🌐 Web Page Won't Load
Symptoms:
- Browser shows "Can't reach this page"
- Connection timeout
- ERR_CONNECTION_REFUSED
Solutions:
-
Verify IP Address
- Check Serial Monitor for exact IP
- Should look like:
192.168.x.xor10.0.x.x - Try typing IP manually (no copy-paste errors)
- Use http:// prefix:
http://192.168.1.100
-
Network Check
- Ensure phone/computer on same WiFi network
- Disable VPN if active
- Disable cellular data on phone
- Check WiFi icon on device
-
ESP32 Status
- Check if still connected (Serial Monitor)
- Look for crashes or reboot loops
- Press RST button to restart
- Re-check IP after restart (may change)
-
Firewall/Security
- Temporarily disable firewall
- Check antivirus blocking
- Try from different device
- Use incognito/private browsing
-
Port 80 Issues
- Check if another service uses port 80
- Try changing port:
WebServer server(8080); // Use port 8080 // Access: http://192.168.1.100:8080
-
DNS/Browser Cache
- Try different browser
- Clear browser cache
- Use IP address (not hostname)
📊 Readings Are Unstable/Jumping
Symptoms:
- Distance values fluctuate wildly
- Readings jump 10+ cm randomly
- Inconsistent measurements
Solutions:
-
Physical Stability
- Mount sensor rigidly (tape, hot glue, clamp)
- Avoid touching breadboard during operation
- Place on stable surface
- Vibrations affect accuracy
-
Measurement Surface
- Use flat, perpendicular surface
- Avoid curved objects
- Don't measure at steep angles
- Sound-absorbing materials cause errors
-
Electrical Noise
- Move away from motors/relays
- Separate sensor wires from power wires
- Add 0.1µF capacitor across VCC-GND
- Use shorter wires
-
Software Filtering Add moving average:
#define SAMPLES 5 float readings[SAMPLES]; int readIndex = 0; float getFilteredDistance() { readings[readIndex] = measureDistance(trigPin, echoPin); readIndex = (readIndex + 1) % SAMPLES; float sum = 0; for (int i = 0; i < SAMPLES; i++) { sum += readings[i]; } return sum / SAMPLES; }
-
Increase Delay
delay(100); // Slower updates = more stable
-
Ignore Invalid Readings
float newDistance = measureDistance(trigPin, echoPin); if (abs(newDistance - currentDistance) < 50) { // Only update if change is reasonable currentDistance = newDistance; }
💾 Upload Fails / Port Not Found
Symptoms:
- Arduino IDE can't find COM port
- Upload error messages
- "Failed to connect" or timeout
Solutions:
-
Install USB Drivers
- CP210x: Silicon Labs
- CH340: Manufacturer site
- Restart computer after installation
- Check Device Manager (Windows) / System Report (Mac)
-
USB Cable Quality
- Try different USB cable (data-capable, not charge-only)
- Test with known-good cable
- Avoid USB hubs (connect directly to computer)
- Try different USB port
-
Driver Detection
- Windows: Check Device Manager → Ports (COM & LPT)
- Mac: Terminal →
ls /dev/cu.* - Linux: Terminal →
ls /dev/ttyUSB*
-
Boot Mode
- Hold BOOT button on ESP32
- Click Upload in Arduino IDE
- Keep holding until "Connecting..." appears
- Release when upload starts
-
Board Selection
Tools → Board → ESP32 Arduino → ESP32 Dev Module Tools → Upload Speed → 115200 (slower = more reliable) -
Linux Permissions
sudo usermod -a -G dialout $USER sudo chmod 666 /dev/ttyUSB0 # Logout and login again
🔄 ESP32 Keeps Rebooting
Symptoms:
- Continuous boot loop
- "Brownout detector" messages
- Resets randomly
Solutions:
-
Power Supply
- Use quality USB cable
- Try 5V 2A power adapter instead of computer USB
- Check for loose connections
- Measure 5V pin: should be stable
-
Reduce Current Draw
WiFi.setSleep(false); // Disable WiFi power saving setCpuFrequencyMhz(160); // Reduce from 240MHz
-
Disable Brownout Detector (temporary):
- Uncomment in code:
// WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); -
Check for Short Circuits
- Remove all connections
- Test bare ESP32
- Add components one by one
| ESP32 Specifications | ||
|---|---|---|
| Parameter | Value | Notes |
| Microcontroller | ESP32 (Dual-core) | Xtensa LX6, 240 MHz |
| Operating Voltage | 3.3V (logic) | 5V via USB/VIN |
| Current Consumption | 80-260mA | Depends on WiFi activity |
| WiFi Standard | 802.11 b/g/n | 2.4 GHz only |
| WiFi Range | 50-100m | Line of sight, outdoor |
| Flash Memory | 4MB | Typical, varies by board |
| RAM | 520KB | SRAM |
| HC-SR04 Sensor Specifications | ||
|---|---|---|
| Parameter | Value | Notes |
| Operating Voltage | 5V DC | ±0.5V tolerance |
| Operating Current | 15mA | Typical |
| Measurement Range | 2 - 400 cm | Effective: 10-300 cm |
| Accuracy | ±3mm | Optimal conditions |
| Resolution | 1cm | Limited by calculation |
| Beam Angle | 15° cone | 30° total spread |
| Ultrasonic Frequency | 40 kHz | 8 pulses per burst |
| Trigger Pulse | 10µs | Minimum requirement |
| Software Performance | ||
|---|---|---|
| Parameter | Value | Configurable |
| Measurement Rate | 20 Hz (50ms) | ✅ Yes |
| Web Update Rate | 5 Hz (200ms) | ✅ Yes |
| Serial Baud Rate | 115200 | ✅ Yes |
| Total System Latency | <100ms | Sensor to UI |
| Web Server Response | <50ms | API endpoint |
| Concurrent Connections | 4-5 | ESP32 limitation |
| Parameter | Range | Impact |
|---|---|---|
| Operating Temperature | -10°C to 60°C | Affects speed of sound |
| Storage Temperature | -20°C to 70°C | Component limits |
| Humidity | 10% - 90% RH | Non-condensing |
| Altitude | 0 - 3000m | Minor accuracy impact |
| Mode | Current Draw | Duration |
|---|---|---|
| WiFi Active (Web Request) | 160-260mA | Continuous |
| Sensor Measurement | +15mA | Per measurement |
| Idle (Connected) | 80-100mA | Between requests |
| Average Total | ~150mA | Typical operation |
Battery Life Estimates:
- 1000mAh battery: ~6-7 hours
- 2000mAh battery: ~12-14 hours
- 5000mAh power bank: ~30+ hours
esp32-distance-monitor/
│
├── 📄 esp32_webserver.ino # Main Arduino sketch
│ ├── WiFi configuration
│ ├── Web server setup
│ ├── Distance measurement function
│ ├── HTML/CSS/JavaScript (embedded)
│ └── API endpoints
│
├── 📁 docs/ # Documentation
│ ├── circuit_diagram.png # Wiring schematic
│ ├── web_interface.png # UI screenshot
│ └── api_examples.md # Integration examples
│
├── 📁 examples/ # Additional examples
│ ├── multiple_sensors.ino # Multi-sensor setup
│ ├── with_oled.ino # OLED display version
│ └── data_logging.ino # SD card logging
│
├── 📖 README.md # This file
├── 📜 LICENSE # MIT License
└── 📝 CHANGELOG.md # Version history
| Version | Date | Changes |
|---|---|---|
| v2.0 (Current) |
Jan 2025 |
✅ Redesigned web interface with modern UI ✅ Added visual range bar indicator ✅ Improved connection status monitoring ✅ Enhanced mobile responsiveness ✅ Added pulsing animation for alerts ✅ Comprehensive documentation update |
| v1.5 | Dec 2024 |
✅ Added JSON API endpoint ✅ Improved error handling ✅ Fixed WiFi reconnection issues ✅ Added configurable thresholds |
| v1.0 | Nov 2024 |
✅ Initial release ✅ Basic web server functionality ✅ HC-SR04 sensor integration ✅ Simple HTML interface |
Contributions are welcome! Help make this project better:
|
Report Bugs Found an issue? Open an issue |
Suggest Features Have an idea? Share it! |
Submit Code Write improvements? Send a PR |
Improve Docs Better explanation? Update README |
- Fork the repository
- Clone your fork:
git clone https://github.com/YOUR-USERNAME/esp32-distance-monitor.git cd esp32-distance-monitor - Create a feature branch:
git checkout -b feature/amazing-feature
- Make your changes
- Test thoroughly on real hardware
- Commit with clear messages:
git commit -m 'Add amazing feature: description' - Push to your fork:
git push origin feature/amazing-feature
- Open a Pull Request
- ✅ Use descriptive variable names
- ✅ Comment complex logic
- ✅ Follow existing formatting (2 spaces, K&R braces)
- ✅ Test on real ESP32 hardware
- ✅ Update documentation for new features
- ✅ Keep backwards compatibility when possible
|
Official Documentation ESP32 Docs Arduino-ESP32 |
Datasheets HC-SR04 Sensor ESP32 Chip |
Community ESP32 Forum r/esp32 |
This project is licensed under the MIT License
Free to use, modify, and distribute with attribution
Click to view full license
MIT License
Copyright (c) 2025 Aryan Ranjan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Special thanks to:
- 🌐 Espressif Systems for the amazing ESP32 platform
- 📖 Arduino Community for comprehensive libraries
- 🔧 Makers & Hackers who share their knowledge
- 🐛 Contributors who help improve this project
- 👥 You for using and supporting this project!
|
Report an Issue Bug reports & feature requests |
Contact Support Private queries |
Documentation Setup & usage |
When Reporting Issues, Please Include:
- ESP32 board model and variant
- Arduino IDE version
- Complete error messages from Serial Monitor
- Photos of your wiring (if hardware-related)
- Steps to reproduce the problem
If this project helped you, please consider:
⭐ Star this repository if you found it helpful!
🍴 Fork it to build your own IoT projects!
📢 Share it with the maker community!
🚀 "The best way to predict the future is to build it." - Alan Kay
Made with ESP32 by Aryan Ranjan
**© 2025 Aryan Ranjan | IoT & Embedded Systems **