An autonomous robot that uses ultrasonic sensing for real-time obstacle detection and collision avoidance. Built with Arduino UNO R4 WiFi and L298N motor driver.
- Overview
- Project Background
- Features
- Hardware Requirements
- Pin Configuration
- Wiring Diagram
- Safety Warnings
- Software Requirements
- Installation & Setup
- Code Architecture
- Algorithm Flow
- Acknowledgments
- License
- Author
The Obstacle Avoiding Car is an autonomous robotic vehicle that navigates its environment by detecting obstacles using an HC-SR04 ultrasonic sensor. The system continuously measures distance to objects ahead and stops movement when obstacles are detected within a 60cm threshold, preventing collisions. The robot resumes forward motion when the path is clear.
This implementation uses the Arduino UNO R4 WiFi (Renesas RA4M1 microcontroller) for control logic, an L298N H-bridge motor driver for dual DC motor control, and ultrasonic ranging for distance measurement.
This project was developed to explore fundamental concepts in autonomous robotics, including:
- Sensor Integration: Working with ultrasonic time-of-flight sensors for distance measurement
- Motor Control: Implementing H-bridge driver circuits for bidirectional DC motor control
- Real-time Decision Making: Creating responsive control algorithms for obstacle avoidance
- Embedded Systems: Programming microcontrollers for real-world hardware interaction
Technical Challenges Addressed:
- Reliable distance measurement with ultrasonic sensors (handling timeouts and echo detection)
- Motor driver interfacing and control signal management
- Real-time loop timing and sensor polling optimization
- Serial debugging for system state monitoring
- Autonomous Navigation: Self-directed forward movement with automatic obstacle detection
- Ultrasonic Distance Sensing: HC-SR04 sensor with 60cm detection threshold
- Dual Motor Control: Independent left/right motor control via L298N driver
- Real-time Serial Output: Distance measurements logged to serial monitor at 9600 baud
- Collision Prevention: Automatic motor stop when obstacles detected
- Simple Control Logic: Straightforward decision tree for easy modification and learning
| Component | Specifications | Quantity |
|---|---|---|
| Arduino UNO R4 WiFi | Renesas RA4M1 (Cortex-M4), 5V logic, USB-C | 1 |
| L298N Motor Driver Module | Dual H-bridge, 5-35V, 2A per channel | 1 |
| DC Motors | 3-12V DC geared motors (TT motors recommended) | 2 |
| HC-SR04 Ultrasonic Sensor | 5V, 2-400cm range, 40kHz | 1 |
| Jumper Wires | Male-to-male and male-to-female | ~15 |
| Power Supply | 7.4V LiPo or 6x AA batteries (9V), 2A minimum | 1 |
| Robot Chassis | 2WD or 4WD platform with motor mounts | 1 |
| Switch | Power on/off switch (optional) | 1 |
Power Supply Notes:
- Motors require external power (cannot run from Arduino 5V rail)
- Recommended: 7.4V 2S LiPo battery or 6x AA battery pack
- L298N requires minimum 7V for stable 5V logic output
| Component | Pin Type | Arduino Pin | L298N/Sensor Pin | Function |
|---|---|---|---|---|
| Right Motor Forward | Digital Output | D4 | IN1 | Drive right motor forward |
| Right Motor Backward | Digital Output | D3 | IN2 | Drive right motor backward |
| Left Motor Forward | Digital Output | D2 | IN3 | Drive left motor forward |
| Left Motor Backward | Digital Output | D5 | IN4 | Drive left motor backward |
| Ultrasonic Trigger | Digital Output | D12 | HC-SR04 Trig | Send 10μs trigger pulse |
| Ultrasonic Echo | Digital Input | D13 | HC-SR04 Echo | Receive echo pulse (max 20ms) |
Pin Definitions in Code:
#define BACKWARDR 3 // Right motor backward
#define FORWARDR 4 // Right motor forward
#define BACKWARDL 5 // Left motor backward
#define FORWARDL 2 // Left motor forward
#define TRIGGER_PIN 12
#define ECHO_PIN 13| L298N Pin | Arduino Pin | Description |
|---|---|---|
| IN1 | D4 | Right motor control 1 |
| IN2 | D3 | Right motor control 2 |
| IN3 | D2 | Left motor control 1 |
| IN4 | D5 | Left motor control 2 |
| GND | GND | Common ground |
| +5V | — | Not connected (L298N provides 5V out) |
| L298N Pin | Connection | Description |
|---|---|---|
| OUT1 | Right Motor + | Right motor positive |
| OUT2 | Right Motor − | Right motor negative |
| OUT3 | Left Motor + | Left motor positive |
| OUT4 | Left Motor − | Left motor negative |
Motor Polarity Note: If a motor runs backwards, swap its + and − connections.
| L298N Pin | Connection | Description |
|---|---|---|
| +12V | Battery + | External power supply (7-12V) |
| GND | Battery − | External power ground |
| +5V OUT | — | Can power Arduino 5V pin (jumper must be installed) |
Important: Remove the L298N 5V regulator jumper if using >12V to prevent damage.
| HC-SR04 Pin | Arduino Pin | Description |
|---|---|---|
| VCC | 5V | Power supply |
| Trig | D12 | Trigger input |
| Echo | D13 | Echo output |
| GND | GND | Ground |
Battery (+) ──→ L298N (+12V)
Battery (−) ──→ L298N (GND) ──→ Arduino (GND)
Arduino (5V) ──→ HC-SR04 (VCC)
Grounding: Ensure Arduino GND and L298N GND share a common ground connection.
- Voltage Limits: Do not exceed 12V input to L298N. Higher voltages may damage the regulator.
- Current Rating: Motors should not exceed 2A per channel. Use appropriate motor selection.
- Heat Dissipation: L298N heatsink may become hot during operation. Avoid direct contact.
- Polarity: Verify battery polarity before connection. Reverse polarity can damage components.
- Short Circuits: Check all connections for shorts before applying power.
- Testing Environment: Test in a safe, open area away from stairs, ledges, or fragile objects.
- Power Switch: Install a power switch for emergency shutoff.
- Motor Stall: Prolonged motor stall (blocked wheels) can overheat the L298N.
- Arduino IDE: Version 2.0 or later recommended (Download)
- Board Package: Arduino Renesas UNO R4 Boards
- Install via: Tools → Board → Boards Manager → Search "Renesas"
- USB Driver: Automatic with Arduino IDE installation
No external libraries required. This project uses only standard Arduino libraries:
- Built-in digital I/O functions
- Built-in serial communication
- Built-in timing functions (
pulseIn,delay,delayMicroseconds)
1. Repository Setup
git clone https://github.com/Legion345/obstacle-avoiding-car.git
cd obstacle-avoiding-car2. Hardware Assembly
- Mount motors to chassis
- Attach wheels to motor shafts
- Secure Arduino and L298N to chassis
- Mount HC-SR04 sensor at front of chassis (facing forward, unobstructed)
3. Wiring Verification
- Double-check all connections against the Wiring Diagram
- Verify motor polarity (test with external power source if uncertain)
- Confirm ultrasonic sensor orientation (sensor face should be forward)
- Ensure common ground between Arduino and L298N
4. Software Installation
- Install Arduino IDE 2.x
- Open Arduino IDE
- Navigate to: Tools → Board → Boards Manager
- Search for "Renesas" and install Arduino Renesas UNO R4 Boards
5. Code Upload
- Open
obstacle_avoiding_car.inoin Arduino IDE - Select board: Tools → Board → Arduino UNO R4 Boards → Arduino UNO R4 WiFi
- Select port: Tools → Port → [Your COM/tty port]
- Click Upload button (or Ctrl+U)
6. Testing & Calibration
- Open Serial Monitor: Tools → Serial Monitor
- Set baud rate to 9600
- Power on the robot (external battery connected to L298N)
- Observe distance readings in Serial Monitor
- Place an object 60cm away and verify robot stops
- Test movement by clearing the path
7. Calibration (if needed)
- If distance readings seem inaccurate, verify:
- Sensor is firmly mounted
- No vibration during operation
- Speed of sound constant is correct for your environment (default: 343 m/s at 20°C)
The code consists of four main components:
1. setup() - Initialization
- Configures motor control pins (D2-D5) as outputs
- Configures ultrasonic sensor pins (D12 trigger, D13 echo)
- Initializes serial communication at 9600 baud
2. loop() - Main Control Logic
- Checks distance: if < 60cm, stops motors; otherwise moves forward
- Triggers ultrasonic sensor with 10μs pulse
- Measures echo pulse duration using
pulseIn()with 20ms timeout - Calculates distance:
distance = duration × 0.0343 / 2 - Logs distance to serial monitor
3. moveForward() - Motor Control
- Activates both motors by setting forward pins HIGH
4. Distance Calculation
- Uses speed of sound (343 m/s or 0.0343 cm/μs at 20°C)
- Divides by 2 to account for sound's round-trip travel
START
↓
[Initialize pins and serial]
↓
├─→ [Check: distanceCm < 60?]
│ ├─ YES → [Stop motors (set forward pins LOW)]
│ │ └─→ [delay(200)]
│ │
│ └─ NO → [moveForward() - activate both motors]
│ └─→ [delay(500)]
↓
[Send ultrasonic trigger pulse]
├─ Set TRIGGER_PIN LOW (2μs)
├─ Set TRIGGER_PIN HIGH (10μs)
└─ Set TRIGGER_PIN LOW
↓
[Measure echo pulse duration]
└─ duration = pulseIn(ECHO_PIN, HIGH, 20000)
↓
[Calculate distance]
└─ distanceCm = duration × 0.0343 / 2
↓
[Log to serial monitor]
└─ Serial.print("Distance: X cm")
↓
[Loop back to decision logic]
└─→ [Continue loop]
Loop Cycle Breakdown:
- Decision + Motor control: ~200-500ms (delay dependent on path status)
- Ultrasonic trigger: ~12μs
- Echo measurement: Variable (0-20ms, depends on distance)
- Distance calculation: <1μs
- Serial output: ~1ms
Total loop time: Approximately 200-520ms per iteration
Effective measurement rate: ~2-5 Hz (adequate for slow-moving robot)
[List any tutorials or resources used during development]
Helpful Resources:
- HC-SR04 Datasheet
- L298N Motor Driver Datasheet
- Arduino UNO R4 WiFi Documentation
- Arduino Community Forums for troubleshooting support
Libraries Used:
- Arduino Core Library (included with Arduino IDE)
This project is licensed under the MIT License.
MIT License
Copyright (c) 2026 Legion345
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.
Legion345
- GitHub: @Legion345
- Project Repository: obstacle-avoiding-car
For questions, suggestions, or collaboration opportunities, feel free to open an issue or reach out via GitHub.
Built with Arduino | Powered by Ultrasonic Sensing | Open Source Hardware