Skip to content

This project implements a distance measurement system using an Arduino UNO and an HC-SR04 ultrasonic sensor, with visual feedback via an LED.

Notifications You must be signed in to change notification settings

aryan-r03/Ultrasonic-Distance-Measurement-System-Arduino-UNO-

Repository files navigation

Typing SVG

Arduino C++ Python Status License

Domain IoT Real-Time


🎯 Portfolio-Grade Embedded Systems Project

Comprehensive distance measurement system demonstrating ultrasonic sensing, real-time signal processing, hardware–software integration, and multi-platform interfacing using Arduino UNO.

⭐ Perfect for academics, portfolio demonstrations, and embedded systems fundamentals


πŸ“‹ Table of Contents


πŸš€ Project Overview

Sensors
Real-Time Sensing
10 Hz sampling rate with HC-SR04
Integration
Multi-Platform
Arduino + Python integration
Professional
Production Ready
Clean, modular, documented

This project implements a comprehensive distance measurement system featuring:

  • 🎯 Real-time distance calculation with visual LED feedback
  • πŸ–₯️ Dual Python interface support (GUI + Audio Alert System)
  • πŸ”” Threshold-based object detection and triggering
  • πŸ“‘ Serial communication protocol for cross-platform integration

Designed to be modular, deterministic, and interview-ready β€” optimized for academic excellence and portfolio demonstrations.


✨ Key Features

Feature Description
⚑ Hardware-Software Integration Seamless Arduino-Python communication via UART
🎨 Multiple Output Modes Compatible with GUI and audio alert systems simultaneously
πŸ”„ Real-time Processing 10 Hz sampling rate with precise distance calculation
πŸ’‘ Visual Feedback LED indicator for proximity alerts (10-40 cm range)
🧩 Modular Design Easy to extend and customize for specific applications
πŸ“ Professional Code Clean, well-documented, interview-ready implementation

🎬 Demo

System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   HC-SR04       β”‚  GPIO   β”‚   Arduino UNO    β”‚  UART   β”‚  Python Host    β”‚
 β”‚  Ultrasonic     β”‚ ──────> β”‚  Microcontroller β”‚ ──────> β”‚   Application   β”‚ 
β”‚    Sensor       β”‚         β”‚                  β”‚         β”‚   (GUI/Audio)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  LED Visual  β”‚
β”‚   Feedback   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Expected Output

Serial Monitor (9600 baud):

25.3
23.7
21.4
PLAY_AUDIO  ← Trigger sent when object in range
20.1
18.9

LED Behavior:

  • 🟒 OFF: Distance > 40 cm or < 10 cm
  • πŸ”΄ ON: Distance between 10-40 cm (object detected)

πŸ“¦ Hardware Requirements

Components List

Component Quantity Purpose Specifications
Arduino UNO 1 Microcontroller ATmega328P, 5V logic
πŸ”Š HC-SR04 Sensor 1 Distance measurement 2-400 cm range, 40 kHz
πŸ’‘ LED (any color) 1 Visual indicator 5mm, 20mA forward current
πŸ”Œ 220Ξ© Resistor 1 LED current limiting 1/4W, Β±5% tolerance
πŸ”— Jumper Wires 6+ Connections Male-to-male
πŸ”Œ USB Type-B Cable 1 Programming & power Data-capable cable

πŸ”Œ Circuit Connections

Pin Mapping

HC-SR04 β†’ Arduino UNO
HC-SR04 Pin Arduino Pin Description
VCC 5V Power supply (+)
GND GND Ground reference
TRIG D9 Trigger pulse input
ECHO D10 Echo pulse output
LED Circuit
LED Terminal Connection
Anode (+) [Long leg] D3 (via 220Ξ© resistor)
Cathode (–) [Short leg] GND

Circuit Diagram

        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚      Arduino UNO            β”‚
        β”‚                             β”‚
                      β”‚  5V  ──────────────────────>β”‚ VCC (HC-SR04)
                      β”‚  GND ──────────────────────>β”‚ GND (HC-SR04)
             β”‚  D9  ──────────────────────>β”‚ TRIG
             β”‚  D10 <──────────────────────│ ECHO
        β”‚                             β”‚
            β”‚  D3  ───[220Ξ©]───>β”‚+LEDβˆ’β”‚β”€β”€>β”‚ GND
        β”‚                             β”‚
                 β”‚  USB <──────────────────────│ Computer
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“Œ Note: For visual circuit diagram, see circuit_diagram.png in repository


🧠 Working Principle

Distance Measurement Algorithm

Step-by-Step Process:

  1. Trigger Phase

    • Arduino sends 10Β΅s HIGH pulse to TRIG pin
  2. Ultrasonic Emission

    • HC-SR04 emits 8 pulses of 40 kHz ultrasonic waves
  3. Echo Detection

    • Waves reflect from object and return to sensor
  4. Time Measurement

    • ECHO pin stays HIGH for duration proportional to distance
  5. Distance Calculation

    Distance (cm) = (Duration Γ— 0.0343) / 2
  6. Threshold Detection

    • LED activates when distance is 10-40 cm
  7. Serial Output

    • Distance values transmitted via UART (9600 baud)

Mathematical Foundation:

Speed of Sound in Air:
  343 m/s = 0.0343 cm/Β΅s

Time-of-Flight:
  Total Time = Distance to Object Γ— 2 / Speed

Distance Formula:
  Distance = (Time Γ— Speed) / 2
  Distance = (Duration Γ— 0.0343) / 2

Why divide by 2?

  • Ultrasonic wave travels to object and back
  • Measured time includes round-trip travel

Measurement Range:

  • Minimum: 2 cm (sensor limitation)
  • Maximum: 400 cm (signal attenuation)
  • Accuracy: Β±3 mm (optimal conditions)

πŸ’» Software Setup

Arduino Development Environment

Arduino
Arduino IDE
Version 1.8.x or 2.x
C++
Language
C/C++ (Arduino Core)
Serial
Communication
UART @ 9600 baud

Python Environment (Optional)

Python
Python 3.8+
PySerial
pyserial
Pygame
pygame
Terminal
Terminal

Install Python dependencies:

pip install pyserial pygame

πŸš€ Quick Start Guide

πŸ“ Step 1: Clone Repository

git clone https://github.com/aryan-r03/ultrasonic-distance-arduino.git
cd ultrasonic-distance-arduino

⚑ Step 2: Upload Arduino Code

  1. Open Arduino IDE
  2. Load arduino_sketch_simple.ino
  3. Connect Arduino UNO via USB
  4. Configure IDE:
    • Tools β†’ Board β†’ Arduino UNO
    • Tools β†’ Port β†’ Select correct port
      • Windows: COM3, COM4, etc.
      • macOS: /dev/cu.usbmodem*
      • Linux: /dev/ttyUSB0, /dev/ttyACM0
  5. Click Upload (β†’ button)
  6. Wait for "Done uploading" message

πŸ” Step 3: Verify Operation

Open Serial Monitor: Tools β†’ Serial Monitor (or Ctrl+Shift+M)

Set to: 9600 baud

Expected Output:

25.3
23.7
21.4
PLAY_AUDIO    ← Trigger when object at 10-40 cm
20.1
18.9

Physical Testing:

  1. Move hand/object in front of sensor
  2. LED should illuminate when object is 10-40 cm away
  3. "PLAY_AUDIO" appears in serial when LED is ON

🐍 Step 4: Run Python Interfaces (Optional)

Option A: GUI Display

python Distance_GUI.py

Features:

  • πŸ“Š Real-time distance visualization
  • 🎨 Color-coded display:
    • 🟒 Green: >50 cm (Safe)
    • 🟑 Yellow: 20-50 cm (Caution)
    • πŸ”΄ Red: <20 cm (Alert)
  • πŸ”Š Text-to-speech announcements

Option B: Audio Alert System

python Distance_custom_audio.py

Features:

  • 🎡 Listens for "PLAY_AUDIO" trigger
  • πŸ”Š Plays sequential audio warnings
  • ⏱️ 5-second cooldown between alerts
  • πŸ“ Custom audio file support

⚠️ Important: Update serial port in Python files:

# macOS
SERIAL_PORT = "/dev/cu.usbmodem101"

# Linux
SERIAL_PORT = "/dev/ttyUSB0"

# Windows
SERIAL_PORT = "COM3"

πŸ”§ Customization

Modify Detection Range

Edit in arduino_sketch_simple.ino:

#define MIN_DISTANCE 10  // Minimum trigger distance (cm)
#define MAX_DISTANCE 40  // Maximum trigger distance (cm)

// Example: Detect objects 20-60 cm away
#define MIN_DISTANCE 20
#define MAX_DISTANCE 60

Adjust Sampling Rate

delay(100);  // Current: 10 Hz (100ms interval)

// Faster sampling (20 Hz)
delay(50);

// Slower sampling (5 Hz)
delay(200);

Change Debounce Period

#define DEBOUNCE_DELAY 1500  // Milliseconds between triggers

// Reduce trigger frequency (3 seconds)
#define DEBOUNCE_DELAY 3000

// Increase trigger frequency (1 second)
#define DEBOUNCE_DELAY 1000

Modify LED Behavior

// Current: LED ON when object in range
digitalWrite(LED_PIN, HIGH);

// Inverse: LED OFF when object in range
digitalWrite(LED_PIN, LOW);

// Blinking LED
digitalWrite(LED_PIN, millis() % 500 < 250 ? HIGH : LOW);

πŸŽ“ Learning Outcomes

Embedded
Embedded Systems
  • Time-of-flight measurement
  • GPIO & digital signals
  • PWM concepts
  • Real-time processing
Software
Software Engineering
  • Serial protocols (UART)
  • Hardware-software integration
  • Multi-platform design
  • State machine implementation
Python
Cross-Platform Dev
  • Python serial communication
  • GUI development
  • Audio processing
  • Real-time data handling
Professional
Professional Skills
  • Clean, maintainable code
  • Comprehensive documentation
  • Modular architecture
  • Version control practices

🌟 Use Cases

πŸŽ“ Academic & Learning

  • πŸ“š Embedded systems labs
  • πŸ”¬ Microcontroller programming
  • πŸ§ͺ Sensor integration demos
  • πŸ“Š Data acquisition projects

πŸš€ Practical Applications

  • πŸ€– Robotics: Navigation systems
  • πŸš— Automotive: Parking assistance
  • 🏠 Smart Home: Automated doors
  • 🏭 Industrial: Presence detection
  • πŸ“‘ IoT: Distance-based triggers

πŸ’Ό Portfolio Enhancement

  • βœ… Hardware-software integration
  • βœ… Multi-language proficiency
  • βœ… Professional documentation
  • βœ… Real-world problem solving
  • βœ… Interview-ready project

πŸ› Troubleshooting

❌ No Serial Output

Solutions:

  • βœ… Check USB connection (use data-capable cable, not charge-only)
  • βœ… Verify correct COM port selected in Arduino IDE
  • βœ… Confirm baud rate is 9600 in Serial Monitor
  • βœ… Check Arduino board selection: Tools β†’ Board β†’ Arduino UNO
  • βœ… Try different USB port on computer
  • βœ… Restart Arduino IDE
πŸ“ Incorrect Distance Readings

Solutions:

  • βœ… Verify HC-SR04 wiring:
    • VCC β†’ 5V
    • GND β†’ GND
    • TRIG β†’ D9
    • ECHO β†’ D10
  • βœ… Ensure sensor has clear line of sight (no obstructions)
  • βœ… Check 5V power supply is stable (measure with multimeter: 4.8-5.2V)
  • βœ… Avoid angled surfaces (use flat, perpendicular objects)
  • βœ… Don't use sound-absorbing materials (foam, fabric)
  • βœ… Test at 20-50 cm distance first (optimal range)
πŸ’‘ LED Not Working

Solutions:

  • βœ… Check LED polarity:
    • Long leg (anode) β†’ 220Ξ© resistor β†’ D3
    • Short leg (cathode) β†’ GND
  • βœ… Verify 220Ξ© resistor is in series (not parallel)
  • βœ… Confirm LED is not burnt out (test with battery)
  • βœ… Check D3 pin connection
  • βœ… Test with multimeter: LED should drop ~2V when ON
🐍 Python Script Connection Errors

Solutions:

  • βœ… Close Arduino Serial Monitor before running Python (port conflict)
  • βœ… Update SERIAL_PORT variable with correct port:
    # Find your port:
    # Windows: Device Manager β†’ Ports (COM & LPT)
    # macOS: ls /dev/cu.*
    # Linux: ls /dev/ttyUSB* /dev/ttyACM*
  • βœ… Check port permissions (Linux/macOS):
    sudo chmod 666 /dev/ttyUSB0
    # or add user to dialout group:
    sudo usermod -a -G dialout $USER
  • βœ… Install required libraries:
    pip install pyserial pygame
  • βœ… Verify Python version: python --version (3.8+)
⚠️ Unstable/Fluctuating Readings

Solutions:

  • βœ… Add smoothing/filtering in code:
    // Moving average of last 5 readings
    float readings[5];
    float average = 0;
    for(int i = 0; i < 5; i++) {
      readings[i] = distance;
      average += readings[i];
    }
    average /= 5;
  • βœ… Increase DEBOUNCE_DELAY to reduce noise
  • βœ… Shield sensor from electromagnetic interference
  • βœ… Use shielded cables for long wire runs
  • βœ… Add decoupling capacitor (0.1Β΅F) across VCC-GND

πŸ“Š Technical Specifications

System Performance

Parameter Value Notes
Operating Voltage 5V DC Regulated from USB (4.8-5.2V)
Current Consumption ~30mA Arduino (15mA) + HC-SR04 (15mA)
Measurement Range 2 cm - 400 cm Effective: 10-300 cm
Accuracy Β±3 mm Under optimal conditions
Resolution 1 cm Limited by calculation
Measurement Angle 15Β° cone 30Β° total beam width
Ultrasonic Frequency 40 kHz 8 pulses per measurement
Sampling Rate 10 Hz 100ms measurement cycle
Serial Baud Rate 9600 UART, 8N1 configuration
Response Time <100 ms Total system latency

Environmental Conditions

Parameter Range
Operating Temperature -10Β°C to 60Β°C
Storage Temperature -20Β°C to 70Β°C
Humidity 10% - 90% RH (non-condensing)

πŸ“‚ Project Structure

ultrasonic-distance-arduino/
β”‚
β”œβ”€β”€ πŸ“„ arduino_sketch_simple.ino          # Main Arduino sketch (RECOMMENDED)
β”œβ”€β”€ πŸ“„ arduino_sketch_compatible.ino      # Advanced mode-selectable version
β”‚
β”œβ”€β”€ 🐍 Distance_GUI.py                    # Real-time GUI display interface
β”œβ”€β”€ 🐍 Distance_custom_audio.py           # Audio alert system
β”‚
β”œβ”€β”€ πŸ–ΌοΈ circuit_diagram.png                # Wiring diagram
β”œβ”€β”€ πŸ“– README.md                          # This file
β”œβ”€β”€ πŸ“œ LICENSE                            # MIT License
β”‚
└── πŸ“ audio_files/                       # Audio alerts (user-provided)
    β”œβ”€β”€ πŸ”Š audio_1.mp3
    β”œβ”€β”€ πŸ”Š audio_2.mp3
    └── πŸ”Š audio_3.mp3

πŸ”„ Version History

Version Timeline

Version Date Changes
v2.0
(Current)
Jan 2025 βœ… Added dual Python interface support
βœ… Implemented mode-selectable operation
βœ… Enhanced serial protocol
βœ… Improved documentation
βœ… Added troubleshooting guide
v1.5 Dec 2024 βœ… Added debounce mechanism
βœ… Improved stability
βœ… Added configuration options
v1.0 Nov 2024 βœ… Basic distance measurement
βœ… LED indicator
βœ… Serial output

🀝 Contributing

Contributions are welcome! Help improve this project:

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch
    git checkout -b feature/enhancement
  3. ✍️ Commit your changes
    git commit -m 'Add amazing enhancement'
  4. πŸ“€ Push to the branch
    git push origin feature/enhancement
  5. πŸ”€ Open a Pull Request

Contribution Guidelines

  • πŸ“ Follow existing code style
  • βœ… Test thoroughly before submitting
  • πŸ“– Update documentation for new features
  • πŸ› Include issue number in PR description
  • πŸ’¬ Provide clear commit messages

πŸ“„ License

This project is licensed under the MIT License

See LICENSE file for complete details

MIT License - Free to use, modify, and distribute
Attribution appreciated but not required

πŸ‘¨β€πŸ’» Author

Author Typing SVG
GitHub LinkedIn
Email Instagram

πŸŽ“ Computer Applications in AI & ML
Building at the intersection of hardware and software


πŸ™ Acknowledgments

Special thanks to:

  • 🌐 Arduino Community for comprehensive documentation
  • πŸ“˜ HC-SR04 Datasheet Authors for technical specifications
  • 🐍 PySerial & Pygame Contributors for Python libraries
  • πŸ‘₯ Open Source Community for continuous inspiration

πŸ“ž Support & Contact

Need Help?

GitHub
Open an Issue
GitHub Issues
Email
Email
Docs
Documentation
See README & Code Comments


🌟 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 customize for your projects!

πŸ“’ Share it with others learning embedded systems!


Footer

πŸ’‘ "Hardware is hard. Software is soft. Integration is magic."



Made with Arduino by Aryan Ranjan


Profile Views



**Β© 2025 Aryan Ranjan | Open Source | IoT & Embedded Systems **

About

This project implements a distance measurement system using an Arduino UNO and an HC-SR04 ultrasonic sensor, with visual feedback via an LED.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published