Skip to content

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.

Notifications You must be signed in to change notification settings

aryan-r03/ESP-32-Distance-Monitor-WebServer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 

Repository files navigation

Typing SVG

ESP32 Arduino WiFi WebServer License

IoT REST API Responsive Real-Time


🌐 Real-Time Ultrasonic Distance Monitoring with Beautiful Web Interface

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

FeaturesDemoQuick StartAPITroubleshooting


📋 Table of Contents


🌟 Project Overview

Sensor
IoT Sensing
HC-SR04 ultrasonic sensor
Real-time measurements
Web
Web Interface
Responsive design
Live data visualization
API
REST API
JSON endpoints
Easy integration
WiFi
WiFi Connected
No cables needed
Access anywhere

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.

🎯 Why This Project?

For Learning:

  • 🎓 Perfect introduction to ESP32 development
  • 🌐 Learn web server implementation
  • 📡 Understand REST API design
  • 🔌 Master sensor integration
  • 📱 Explore responsive web design

For Building:

  • 🚀 Production-ready code quality
  • 🎨 Modern, beautiful UI design
  • 🔧 Easy to customize and extend
  • 📊 Real-time data visualization
  • 💼 Portfolio-worthy project

✨ Key Features

Core Capabilities

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

🎬 Demo & Preview

Web Interface Behavior

✅ Safe Zone

Safe

🟢 Green background
All clear status
Calm appearance
No alerts triggered

⚠️ Warning Zone

Warning

🟡 Yellow background
Object approaching
Cautious state
Monitoring active

🚨 Alert Zone

Alert

🔴 Red background
Object very close
Pulsing animation
Immediate attention

Interface Layout

┌────────────────────────────────────────────────────┐
 │              ESP32 Distance Monitor                │ 
│             Real-Time Web Interface                │
│                                                    │
│    ┌──────────────────────────────────────────┐    │
│    │         ✓ All Clear - Safe Zone          │    │
│    └──────────────────────────────────────────┘    │
│                                                    │
│                  25.3 cm                           │
│              ━━━━━━━━━━━━━━                        │
│                                                    │
│    ├────────────●───────────────────────────┤      │
│    0cm         25cm                      100cm     │
│                                                    │
│          Connected | Last update: 0.2s ago         │
└────────────────────────────────────────────────────┘

System Flow Diagram

┌─────────────┐         ┌──────────────┐         ┌────────────────┐
│  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

📦 Hardware Requirements

Essential Components

Component Quantity Specifications Purpose
ESP32 Dev Board 1 ESP32-WROOM, NodeMCU-32S, or similar Main microcontroller with WiFi
🔊 HC-SR04 Sensor 1 4-pin ultrasonic, 40kHz, 2-400cm range Distance measurement
🔗 Jumper Wires 4 Male-to-female recommended Sensor connections
🍞 Breadboard 1 Half or full size (optional) Prototyping and testing
🔌 USB Cable 1 Micro-USB or USB-C (board dependent) Programming and power

Optional Components

Power
5V Power Supply
For standalone operation
Enclosure
Project Enclosure
3D printed or commercial case
LED
LED Indicators
Additional visual feedback
OLED
OLED Display
Standalone local readout

Cost Estimate

Item Approximate Cost
ESP32 Board $5-15
HC-SR04 Sensor $2-5
Jumper Wires & Breadboard $3-8
USB Cable $2-5
Total $12-33

🔌 Circuit Connections

Pin Mapping & Wiring

Standard Connection Diagram:

HC-SR04 Sensor          ESP32 Board
┌──────────────┐       ┌──────────────┐
│              │       │              │
│     VCC  ────┼───────┼──── 5V       │
│              │       │              │
│     TRIG ────┼───────┼──── GPIO 18  │
│              │       │              │
│     ECHO ────┼───────┼──── GPIO 19  │
│              │       │              │
│     GND  ────┼───────┼──── GND      │
│              │       │              │
└──────────────┘       └──────────────┘

Pin Configuration Table:

HC-SR04 Pin ESP32 Pin Wire Color* Function
VCC 5V Red Power (+)
TRIG GPIO 18 Yellow Trigger pulse
ECHO GPIO 19 Blue Echo response
GND GND Black Ground (-)

*Suggested colors for easy identification

⚠️ Important Voltage Note

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:

  1. Direct Connection (Most Common)

    • Connect ECHO directly to GPIO 19
    • Works in 99% of cases with no issues
    • Convenient for prototyping
  2. Voltage Divider (Safest)

    ECHO ──┬── 1kΩ ──┬── GPIO 19
           │          │
           └── 2kΩ ──┴── GND
    
    • Reduces 5V to 3.3V safely
    • Recommended for long-term/production use
  3. 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.

Custom Pin Configuration

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 pin

Recommended 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

💻 Software Setup

Development Environment

Arduino
Arduino IDE
Version 1.8.x or 2.x
Download
ESP32
ESP32 Board Support
By Espressif Systems
Version 2.x or later
USB
USB Drivers
CP210x or CH340
Board dependent

Required Libraries

Built-in Libraries (No installation needed):

  • WiFi.h - ESP32 WiFi connectivity
  • WebServer.h - HTTP web server functionality

All dependencies come with the ESP32 board package! 🎉


🚀 Quick Start Guide

📥 Step 1: Install Arduino IDE & ESP32 Support

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 FilePreferences
  • In "Additional Board Manager URLs", add:
    https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
    
  • Click OK
  • Go to ToolsBoardBoards Manager
  • Search for "esp32"
  • Install "esp32 by Espressif Systems" (latest version)
  • Wait for installation to complete

3. Install USB Drivers (if needed):

⚙️ Step 2: Configure the Project

  1. Clone or Download this repository:

    git clone https://github.com/your-username/esp32-distance-monitor.git
    cd esp32-distance-monitor
  2. Open esp32_webserver.ino in Arduino IDE

  3. 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
  4. Verify Pin Configuration (lines 10-11):

    const int trigPin = 18;    // HC-SR04 TRIG pin
    const int echoPin = 19;    // HC-SR04 ECHO pin
  5. 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)

⬆️ Step 3: Upload to ESP32

Select Board:

  1. Go to ToolsBoard
  2. Select ESP32 Arduino → Your board model
    • Common: ESP32 Dev Module
    • Or: NodeMCU-32S, DOIT ESP32 DEVKIT V1

Select Port:

  1. Go to ToolsPort
  2. Choose the COM/USB port
    • Windows: COM3, COM4, etc.
    • macOS: /dev/cu.usbserial-*
    • Linux: /dev/ttyUSB0, /dev/ttyACM0

Upload Settings:

  • Upload Speed: 921600 (or 115200 if issues)
  • CPU Frequency: 240MHz
  • Flash Frequency: 80MHz
  • Flash Mode: QIO
  • Flash Size: 4MB (or your board's size)
  • Partition Scheme: Default

Upload Process:

  1. Click Upload button (→)
  2. Wait for "Connecting..."
  3. If stuck: Hold BOOT button on ESP32
  4. Wait for "Hard resetting via RTS pin..."

🔍 Step 4: Monitor Serial Output

  1. Open Serial Monitor: ToolsSerial Monitor (or Ctrl+Shift+M)
  2. Set baud rate to 115200
  3. 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

🌐 Step 5: Access Web Interface

  1. Note the IP address from Serial Monitor (e.g., 192.168.1.100)
  2. Open any web browser on your phone/computer
  3. Navigate to: http://YOUR_ESP32_IP
    • Example: http://192.168.1.100
  4. 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

⚙️ Configuration

Essential Settings

🌐 WiFi Configuration

// Network credentials
const char* ssid = "YourWiFiName";
const char* password = "YourPassword";

Tips:

  • SSID is case-sensitive
  • Use 2.4GHz network (ESP32 doesn't support 5GHz)
  • Avoid special characters in SSID if possible
  • Password must match exactly

📡 Sensor Pin Assignment

// GPIO pin configuration
const int trigPin = 18;  // Trigger output
const int echoPin = 19;  // Echo input

Best Practices:

  • Use 5V-tolerant pins for ECHO
  • Avoid boot-mode pins (0, 2, 12, 15)
  • Keep wires short for reliability
  • Test with multimeter if issues occur

Advanced Configuration

📏 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 averaging

Guidelines:

  • 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 traffic

Best 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";
}

🧠 System Architecture

Complete System Flow

┌──────────────────────────────────────────────────────────────────┐
│                         ESP32 System Architecture                │
│                                                                  │
│  ┌──────────────┐      ┌─────────────┐      ┌─────────────────┐  │
│  │  HC-SR04     │ GPIO │   ESP32     │ WiFi │  Web Browser    │  │
│  │  Ultrasonic  │─────▶│   Core      │◀────▶│   (Client)      │  │
│  │   Sensor     │      │             │      │                 │  │
│  └──────────────┘      └──────┬──────┘      └─────────────────┘  │
│                               │                                  │
│                               ▼                                  │
│                        ┌─────────────┐                           │
│                        │ Web Server  │                           │
│                        │  (Port 80)  │                           │
│                        └──────┬──────┘                           │
│                               │                                  │
│                    ┌──────────┴──────────┐                       │
│                    │                      │                      │
│              ┌─────▼──────┐        ┌────▼─────┐                  │
│              │     /      │        │   /data  │                  │
│              │  (HTML UI) │        │  (JSON)  │                  │
│              └────────────┘        └──────────┘                  │
└──────────────────────────────────────────────────────────────────┘

Measurement Process (Time-of-Flight)

Physical Process:

  1. Trigger Phase

    • ESP32 sends 10µs HIGH pulse to TRIG
    • HC-SR04 prepares ultrasonic burst
  2. Emission Phase

    • Sensor emits 8 pulses at 40 kHz
    • Ultrasonic waves propagate through air
  3. Reflection Phase

    • Waves hit object and reflect back
    • Return to sensor's receiver
  4. Detection Phase

    • ECHO pin goes HIGH when burst sent
    • ECHO pin goes LOW when echo received
    • Duration = time between HIGH and LOW
  5. Calculation Phase

    • ESP32 measures pulse duration
    • Applies distance formula

Mathematical Foundation:

Speed of Sound in Air:
  v = 343 m/s = 0.0343 cm/µs
  (at 20°C, sea level)

Time-of-Flight Formula:
  Total Time = 2 × Distance / Speed
  
Distance Calculation:
  Distance = (Time × Speed) / 2
  Distance = (Duration × 0.0343) / 2
  Distance = Duration × 0.01715

Example:
  Duration = 1000 µs
  Distance = 1000 × 0.01715
  Distance = 17.15 cm

Why divide by 2?

  • Sound travels TO object
  • Then BACK to sensor
  • Total = round trip
  • Distance is one-way only

Data Flow Timeline

Sensor Reading → Distance Calc → Web Server → API Response → Browser → UI Update
     (50ms)       (instant)       (minimal)      (10-50ms)    (instant)   (smooth)
     
     └──────────────────────────────────────────────────────────────┘
                    Total latency: < 100ms

Web Request Flow

┌─────────────┐                    ┌──────────────┐
│   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)  │
       ├─────────────────────────────────▶│
       │                                  │

📡 API Reference

REST API Endpoints

GET /

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/

GET /data

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 error
  • distance: -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 successfully
  • 500 Internal Server Error - Sensor malfunction

Integration Examples

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

🎨 Customization

Extension Ideas

🔔 Add Notifications

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();
}

📊 Data Logging

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
}

🐛 Troubleshooting

Common Issues & Solutions

❌ 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:

  1. 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
  2. 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
  3. Signal Strength

    • Move ESP32 closer to router
    • Check for physical obstacles
    • Avoid metal enclosures during testing
  4. 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
  5. Reset ESP32

    • Hold BOOT button while pressing RST
    • Release RST, then release BOOT
    • Re-upload sketch
  6. 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:

  1. 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
  2. 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
  3. 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
  4. 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;
  5. 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
  6. 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:

  1. Verify IP Address

    • Check Serial Monitor for exact IP
    • Should look like: 192.168.x.x or 10.0.x.x
    • Try typing IP manually (no copy-paste errors)
    • Use http:// prefix: http://192.168.1.100
  2. Network Check

    • Ensure phone/computer on same WiFi network
    • Disable VPN if active
    • Disable cellular data on phone
    • Check WiFi icon on device
  3. 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)
  4. Firewall/Security

    • Temporarily disable firewall
    • Check antivirus blocking
    • Try from different device
    • Use incognito/private browsing
  5. 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
  6. 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:

  1. Physical Stability

    • Mount sensor rigidly (tape, hot glue, clamp)
    • Avoid touching breadboard during operation
    • Place on stable surface
    • Vibrations affect accuracy
  2. Measurement Surface

    • Use flat, perpendicular surface
    • Avoid curved objects
    • Don't measure at steep angles
    • Sound-absorbing materials cause errors
  3. Electrical Noise

    • Move away from motors/relays
    • Separate sensor wires from power wires
    • Add 0.1µF capacitor across VCC-GND
    • Use shorter wires
  4. 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;
    }
  5. Increase Delay

    delay(100);  // Slower updates = more stable
  6. 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:

  1. Install USB Drivers

  2. 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
  3. Driver Detection

    • Windows: Check Device Manager → Ports (COM & LPT)
    • Mac: Terminal → ls /dev/cu.*
    • Linux: Terminal → ls /dev/ttyUSB*
  4. Boot Mode

    • Hold BOOT button on ESP32
    • Click Upload in Arduino IDE
    • Keep holding until "Connecting..." appears
    • Release when upload starts
  5. Board Selection

    Tools → Board → ESP32 Arduino → ESP32 Dev Module
    Tools → Upload Speed → 115200 (slower = more reliable)
    
  6. 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:

  1. 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
  2. Reduce Current Draw

    WiFi.setSleep(false);  // Disable WiFi power saving
    setCpuFrequencyMhz(160);  // Reduce from 240MHz
  3. Disable Brownout Detector (temporary):

    • Uncomment in code:
    // WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  4. Check for Short Circuits

    • Remove all connections
    • Test bare ESP32
    • Add components one by one

📊 Technical Specifications

System Performance

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

Environmental Conditions

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

Power Consumption Profile

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

📂 Project Structure

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 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

🤝 Contributing

Contributions are welcome! Help make this project better:

Ways to Contribute

Bug
Report Bugs
Found an issue?
Open an issue
Feature
Suggest Features
Have an idea?
Share it!
Code
Submit Code
Write improvements?
Send a PR
Docs
Improve Docs
Better explanation?
Update README

Development Workflow

  1. Fork the repository
  2. Clone your fork:
    git clone https://github.com/YOUR-USERNAME/esp32-distance-monitor.git
    cd esp32-distance-monitor
  3. Create a feature branch:
    git checkout -b feature/amazing-feature
  4. Make your changes
  5. Test thoroughly on real hardware
  6. Commit with clear messages:
    git commit -m 'Add amazing feature: description'
  7. Push to your fork:
    git push origin feature/amazing-feature
  8. Open a Pull Request

Code Style Guidelines

  • ✅ 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

📚 Additional Resources


📄 License

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.

🙏 Acknowledgments

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!

👨‍💻 Author

Author Typing SVG
GitHub LinkedIn
Email Instagram

🎓 Computer Applications in AI & ML
Building innovative IoT and embedded systems solutions


📞 Support & Contact

Need Help?

Issues
Report an Issue

Bug reports & feature requests
Support
Contact Support

Private queries
Docs
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

🌟 Show Your Support

If this project helped you, please consider:

GitHub stars GitHub forks GitHub watchers



⭐ Star this repository if you found it helpful!

🍴 Fork it to build your own IoT projects!

📢 Share it with the maker community!


Footer

🚀 "The best way to predict the future is to build it." - Alan Kay



Made with ESP32 by Aryan Ranjan


Profile Views



**© 2025 Aryan Ranjan | IoT & Embedded Systems **


About

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.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages