🤖 Arduino Smart Robot System

Complete Build Guide: Ultrasonic Radar + Line Following

📋 Project Overview

This project combines two cutting-edge robotics systems into one intelligent autonomous platform. The robot features:

1

🎯 360° Obstacle Detection

HC-SR04 ultrasonic sensor mounted on servo motor performs continuous environmental scanning with radar-like capability.

2

➡️ Precision Line Following

Dual IR sensors track black/white lines with adaptive speed control and smooth curve navigation.

3

🧠 Intelligent Decision Making

Arduino Uno processes multi-sensor data in real-time and executes complex behavioral algorithms.

4

⚡ Powerful Motor Control

Three independent DC motors with L298N driver provide smooth, synchronized motion control.

System Architecture Diagram

Arduino Smart Robot Architecture Arduino Uno (Brain/Controller) HC-SR04 Ultrasonic Line Sensors (Left + Right) DC Motors (2x Wheels) Servo Motor (Sensor Rotation) 7.4V Battery Pack Powers all motors via L298N

🔧 Complete Component List & Pricing

✓ Verified Components: This list matches the actual wiring diagram image and includes all necessary components for complete assembly.
# Component Name Quantity Specification Unit Price (BDT) Total (BDT) Purpose
1 Arduino Uno Rev3 1 ATmega328P, 16MHz Clock ৳900 ৳900 Main Controller/Microcontroller
2 HC-SR04 Ultrasonic Sensor 1 5V, 2cm-400cm Range ৳120 ৳120 Obstacle Detection & Distance Measurement
3 Infrared Line Sensor Module 2 5V, Analog Output, Adjustable ৳150 each ৳300 Left & Right Line Detection
4 SG90 Servo Motor 1 5V, 0-180°, 10g Torque ৳250 ৳250 Rotate Ultrasonic Sensor for 360° Scan
5 DC Gear Motor (Yellow/Black) 2 6V, 200RPM, Metal Gears, 0.5kg Torque ৳280 each ৳560 Left & Right Wheel Drive
6 L298N Motor Driver Module 1 Dual Channel, 2A Max, PWM Speed Control ৳320 ৳320 Motor Control & Direction Management
7 7.4V Li-ion Battery Pack 1 2x18650 Lithium Cells, 1500mAh, Protected ৳750 ৳750 Main Power Supply for Motors
8 Battery Connector & Holder 1 JST XT60 / Tamiya Connector with Wires ৳180 ৳180 Safe Battery Connection & Hot Swap
9 Slide On/Off Power Switch 1 5A Capacity, 2-Pin ৳50 ৳50 Safe Power Management (visible in diagram)
10 Robot Chassis (3WD/4WD) 1 170x140mm, Aluminum Frame, Wheels Included ৳700 ৳700 Robot Body & Structural Support
11 Breadboard (830 point) 2 Full Size, Self-Adhesive Back ৳150 each ৳300 Prototyping & Circuit Layout (as shown)
12 Jumper Wire Set 1 set Male-Male & Male-Female, 20+ pieces, Assorted Colors ৳200 ৳200 Component Interconnection
13 USB Type-A to B Cable 1 2.0 Standard, Arduino Compatible ৳120 ৳120 Arduino Programming & Serial Communication
14 Servo Motor Bracket 1 Metal Mount, Ultrasonic Sensor Adapter ৳80 ৳80 Mount Servo & HC-SR04 Together
15 Motor Wheel Coupling 2 Motor Shaft to Wheel Adapter ৳40 each ৳80 Connect Motors to Wheels
16 Capacitors Assortment 1 set 100μF, 10μF (Ceramic & Electrolytic) ৳150 ৳150 Noise Filtering & Power Stabilization
17 Resistors Assortment 1 set Various values (1k, 10k, 220Ω, etc.) ৳100 ৳100 Sensor Calibration & Safety Protection
18 Super Glue & Hot Glue Gun 1 set Multi-purpose Adhesive + Glue Sticks ৳200 ৳200 Assembly & Component Mounting
19 Heat Shrink Tubing Set 1 set Various diameters, Assorted Colors ৳150 ৳150 Wire Protection & Professional Finish
20 Workstation Mat & Tools 1 set Soldering Mat, Cutting Mat, Mini Tools ৳400 ৳400 Safe Assembly & Soldering Workspace

TOTAL PROJECT COST

৳6,530

Complete System (All Components Included)

Prices accurate for Bangladesh market (February 2026) • May vary by supplier & location • Includes all necessary components for assembly, testing, and programming

⚠️ Cost Optimization Tips:
  • Buy components from local electronics shops (Naya Paltan, Mayur Electronics)
  • Negotiate bulk pricing for resistors/capacitors
  • Second-hand Arduino Uno: ৳500-600 (save ৳300-400)
  • DIY chassis from cardboard/foam (save ৳400-500)
  • Skip premium soldering tools if using breadboard only

✅ Components Verification Against Wiring Diagram Image

✓ Verified in Diagram:

  • HC-SR04 with servo mounted on top
  • Arduino Uno (center board)
  • L298N motor driver (red board with heat sink)
  • 7.4V Li-ion battery pack (2x18650)
  • Two DC gear motors (yellow/black)
  • Two IR line sensors (bottom right)
  • Breadboards for prototyping
  • Jumper wires (multiple colors)
  • Slide switch for power control
  • USB cable for programming

❗ Essential Components NOT Visible (But Required)

Must-Have Additions:

1. Capacitors: 100μF across motor power lines (prevents voltage spikes)

2. Heat Shrink Tubing: Professional finish and wire safety

3. Servo Bracket: To mount ultrasonic sensor on servo motor

4. Motor Couplings: Connect motor shafts to wheels properly

These components were added because they're essential for reliable operation and longevity of the robot.

🔌 Detailed Wiring Connections

⚠️ CRITICAL SAFETY: Always use a common ground between battery and Arduino. Double-check all connections before powering on. Use a multimeter to verify connections.

Pin-by-Pin Connection Guide

1. HC-SR04 Ultrasonic Sensor → Arduino

VCC → Arduino 5V Power Supply (Red Wire)
GND → Arduino GND Ground Connection (Black Wire)
TRIG → Arduino Pin 7 Trigger Pulse (Yellow Wire)
ECHO → Arduino Pin 8 Echo Response (Blue Wire)

2. Line Sensors (IR) → Arduino

LEFT SENSOR:

VCC → Arduino 5V Power Supply
GND → Arduino GND Ground Connection
OUT → Arduino A0 Analog Sensor Output

RIGHT SENSOR:

VCC → Arduino 5V Power Supply
GND → Arduino GND Ground Connection
OUT → Arduino A1 Analog Sensor Output

3. SG90 Servo Motor → Arduino

BROWN (GND) → Arduino GND Ground Connection
RED (VCC) → Arduino 5V Power Supply (or separate 5V)
ORANGE (SIG) → Arduino Pin 9 (PWM) Servo Control Signal

4. L298N Motor Driver → Arduino & Motors

POWER CONNECTIONS:

GND (Module) → Battery GND + Arduino GND CRITICAL: Common Ground
+12V / +5V → Battery + (7.4V) Motor Power Input

MOTOR 1 CONTROL (Left Wheel):

IN1 → Arduino Pin 2 Direction A
IN2 → Arduino Pin 3 Direction B
ENA → Arduino Pin 10 (PWM) Speed Control (0-255)
OUT1 & OUT2 → Motor 1 Terminals Motor Connection

MOTOR 2 CONTROL (Right Wheel):

IN3 → Arduino Pin 4 Direction A
IN4 → Arduino Pin 5 Direction B
ENB → Arduino Pin 11 (PWM) Speed Control (0-255)
OUT3 & OUT4 → Motor 2 Terminals Motor Connection

5. Power Distribution

Battery + (7.4V) → L298N +12V & Switch Motor Power Supply
Battery GND → L298N GND & Arduino GND MUST be common ground
Arduino 5V → All Sensors & Servo Limited to ~500mA

Visual Wiring Diagram (SVG)

Complete Wiring Schematic Arduino Uno 5V GND Pin 2-11 A0-A1 5V GND HC-SR04 Ultrasonic TRIG→Pin7 ECHO→Pin8 Line Sensors IR1 + IR2 A0-A1 L298N Motor Driver GND +12V 5V Motor 1 Left Wheel Motor 2 Right Wheel Servo Motor (SG90) Pin 9 PWM 7.4V Battery Pack

⚙️ Step-by-Step Assembly Guide

Phase 1: Chassis & Motor Preparation (2-3 hours)

1

Mount DC Motors on Chassis

Attach the two 200RPM gear motors to the front left and right sides of the chassis using metal L-brackets and M3 screws. Ensure motor shafts point downward and rotate freely without obstruction.

⚠️ Alignment critical: Motors must be parallel for straight-line movement.

2

Attach Wheels to Motor Shafts

Mount the wheels onto the motor shafts using the coupling adapters. Ensure wheels are centered and balanced. Spin manually to verify smooth rotation with no wobble.

✓ Check: Wheels should spin freely at least 10 revolutions without stopping.

3

Install Battery Holder

Mount the battery holder on the chassis bottom using double-sided foam tape or Velcro strips. Position centrally to maintain balance. Route battery connector wires along the chassis edge toward the power switch.

⚠️ Safety: Install ON/OFF slide switch in the battery positive line.

4

Mount Control Boards

Use Velcro strips to secure Arduino Uno and L298N motor driver on the chassis top. Arduino should be centered front; L298N placed near the motors to minimize wire lengths. This arrangement allows easy access to USB port for programming.

💡 Tip: Leave 2-3cm spacing between boards for airflow and component access.

Phase 2: Sensor Installation (1-2 hours)

5

Mount Line Sensors Underneath

Install the two IR line sensors on the chassis bottom front, 4-5cm apart. Mount them exactly 1.5-2cm above the ground using flexible brackets. The sensors must face downward to detect the black/white line beneath the robot.

⚠️ Critical: Height adjustment determines detection accuracy. Test before final mounting.

6

Install Servo & Ultrasonic Sensor Mount

Secure SG90 servo motor on the chassis top-center using a metal bracket. Attach the HC-SR04 ultrasonic sensor to the servo motor arm using the sensor bracket adapter. This creates a rotating radar head that scans 180° (or full 360° with modifications).

💡 Tip: Secure wires along servo arm to prevent tangling during rotation.

Phase 3: Electrical Connections (2-3 hours)

7

Create Power Distribution on Breadboard

Use breadboards to organize power distribution. Connect the positive rail to battery + (through switch), negative rail to battery GND. This creates clean power distribution for all sensors. Use 100μF capacitors across motor power inputs for noise filtering.

⚠️ Critical: Ensure common ground between battery and Arduino (use GND jumper wire).

8

Connect HC-SR04 Ultrasonic Sensor

Wire the ultrasonic sensor following the pin map: VCC→5V, GND→GND, TRIG→Pin7, ECHO→Pin8. Use color-coded jumper wires: Red for power, Black for ground, Yellow for TRIG, Blue for ECHO. Double-check all connections before powering.

✓ Test: Upload test sketch, verify distance readings in Serial Monitor.

9

Connect Line Sensors

Left sensor: VCC→5V, GND→GND, OUT→A0. Right sensor: VCC→5V, GND→GND, OUT→A1. Keep sensor wires together and away from motor wires to minimize noise interference. Use shielded cable if possible.

✓ Test: Place on white/black surfaces, observe analog values changing (should differ by 100+ points).

10

Connect Servo Motor

Servo has three wires: Brown (GND)→Arduino GND, Red (VCC)→Arduino 5V, Orange (Signal)→Arduino Pin 9 (PWM). If servo drawing too much current, use separate 5V power supply for servo only. Connect 100μF capacitor across servo power pins.

⚠️ Warning: 200mA servo current + sensors can exceed Arduino 5V output. Consider external 5V supply.

11

Connect L298N Motor Driver

Motor 1: IN1→Pin2, IN2→Pin3, ENA→Pin10. Motor 2: IN3→Pin4, IN4→Pin5, ENB→Pin11. Connect +12V to battery+ and GND to battery GND (MUST be same as Arduino GND). OUT terminals connect to motor leads. Use solder for reliable connections.

⚠️ Critical: Motor polarity determines rotation direction. Test direction and swap wires if needed.

12

Final Verification & Testing

Before powering on: Use multimeter to verify battery voltage (7-8V), check for short circuits (resistance between ±), confirm common ground connections. Power on without motors connected first. Check LED lights on Arduino and L298N. Then test motors individually.

✓ Success: Arduino powers up, no sparks, no burn smell, motors can be controlled separately.

✅ Assembly Complete! Your robot is now mechanically and electrically assembled. Time to move to programming and testing phases.

🎬 Step-by-Step Simulation & Testing

Stage 1: Individual Component Testing (No Load)

1

Power-On Test (Safety Check)

Action: Connect battery. Arduino LED should light. L298N indicator LEDs should turn on.

Expected: No sparks, no burning smell, no excessive heat.

If problem: Disconnect immediately. Check for short circuits using multimeter.

2

Motor Direction Test

Action: Hold robot in air. Upload motor test code. Activate Motor 1 forward.

Expected: Left wheel spins clockwise (adjust code if counter-clockwise).

Adjustment: If reverse, swap motor terminal connections or flip HIGH/LOW logic in code.

3

Motor Speed Test

Action: Gradually increase PWM value (0→255) using analogWrite.

Expected: Motor speed increases smoothly. No grinding or jerking noise.

Measure: Motor stalls at PWM < 100. Smooth operation at PWM 150-255.

4

Servo Scan Test

Action: Upload servo test code. Servo should sweep 0°→180°→0°.

Expected: Smooth rotation without jerking or grinding. HC-SR04 rotates with servo.

Measure: Each sweep takes ~3-4 seconds. Current draw <200mA.

5

Ultrasonic Sensor Test

Action: Open Serial Monitor (9600 baud). Move hand in front of sensor.

Expected: Distance readings change (0-400cm range). No negative values.

Verify: 5cm distance shows ~50 on display. 30cm distance shows ~300. Linear relationship.

6

Line Sensor Calibration

Action: Read analog values. Place on white paper. Note value (e.g., 200). Place on black line. Note value (e.g., 800).

Expected: Minimum 300-point difference between white/black. Adjust potentiometers if gap <200.

Calibration: Set threshold at midpoint: (200+800)/2 = 500 in code.

Stage 2: System Integration Testing

7

Forward Motion Test

Setup: Place robot on table. No obstacles. Upload integrated code.

Expected: Robot moves forward in straight line. Speed consistent.

Measure: Travel 1 meter in ~5-8 seconds at PWM 200. Adjust motor speeds if drifting left/right.

8

Line Following Test

Setup: Create test track with black tape on white paper (30-50cm width). Curves optional.

Expected: Robot follows line smoothly. Corrects drift automatically. Completes track without falling off.

Metrics: Time to complete track. Number of corrections. Success rate (>95%).

9

Obstacle Detection Test

Setup: Robot moving forward. Place hand/object ~30cm ahead.

Expected: Robot stops before obstacle. Servo scans left/right. Backs up and turns.

Measure: Stopping distance < 10cm. Detection reliability >90%.

10

Radar Visualization

Action: Upload code with Serial output. Run Processing/Python script to display radar graphics.

Expected: Green radar arc shows obstacles as red dots. Real-time updates as servo scans.

Output: Visual confirmation of ultrasonic sensor accuracy and scanning pattern.

Stage 3: Real-World Autonomous Operation

11

Long-Duration Line Following

Test: Robot follows line for 5-10 minutes continuously.

Monitor: Battery voltage (should stay >6.5V). Temperature of L298N (should stay <50°C). Motor behavior (no stalling).

Success: Completes multiple laps without requiring intervention.

12

Complex Navigation Test

Setup: Multi-room house or outdoor area with obstacles, ramps, corners.

Test: Robot navigates independently, avoids obstacles, recovers from line loss.

Success Criteria: Completes path without external help. Adapts to changing light conditions.

Test Data Logging Template

Data to Record:

Date: __/__/____          Test Location: ________________

COMPONENT TESTS:
✓ Motors: L____RPM  R____RPM  (Rotation direction: OK/SWAP)
✓ Servo: Min___°  Max___°  Speed: __°/sec
✓ Ultrasonic: Min___cm  Max___cm  Accuracy: ±__cm
✓ Line Sensors: White-Value____  Black-Value____  Difference____

INTEGRATION TESTS:
✓ Forward Motion: Time for 1m: ____ sec  (Target: 5-8 sec)
✓ Line Following: Success Rate: ___% Oscillation: None/Slight/Heavy
✓ Obstacle Avoidance: Detection Distance: __cm  Recovery: OK/Fail
✓ Battery Life: Runtime: ____ min  Final Voltage: __ V

ISSUES FOUND & FIXES:
1. _________________________________ → Fixed by: ______________
2. _________________________________ → Fixed by: ______________
3. _________________________________ → Fixed by: ______________

NEXT STEPS:
□ PID Tuning needed for line following
□ Servo power supply upgrade required
□ Motor speed synchronization adjustment
□ Sensor calibration optimization
□ Code optimization for battery life
                

💻 Arduino Sketch Code

Main Control Program

This complete sketch handles all robot functions: motor control, sensor reading, obstacle detection, and line following.

// ===================================================== // Arduino Smart Robot - Main Control Program // Ultrasonic Radar + Line Following System // ===================================================== #include <NewPing.h> #include <Servo.h> // ===== PIN DEFINITIONS ===== #define TRIG_PIN 7 #define ECHO_PIN 8 #define SERVO_PIN 9 #define LEFT_SENSOR A0 #define RIGHT_SENSOR A1 #define M1_IN1 2 #define M1_IN2 3 #define M2_IN3 4 #define M2_IN4 5 #define ENA_PIN 10 #define ENB_PIN 11 // ===== CONSTANTS ===== #define MAX_DISTANCE 200 #define OBSTACLE_THRESHOLD 20 #define MOTOR_MAX_SPEED 255 #define LINE_THRESHOLD 500 // ===== OBJECT INITIALIZATION ===== NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); Servo servoMotor; // ===== GLOBAL VARIABLES ===== int leftSensor, rightSensor; int servoAngle = 90; int motorSpeed = 200; unsigned long lastScanTime = 0; const int SCAN_INTERVAL = 500; // Scan every 500ms // ===== SETUP ===== void setup() { Serial.begin(9600); // Initialize Motor Pins pinMode(M1_IN1, OUTPUT); pinMode(M1_IN2, OUTPUT); pinMode(M2_IN3, OUTPUT); pinMode(M2_IN4, OUTPUT); pinMode(ENA_PIN, OUTPUT); pinMode(ENB_PIN, OUTPUT); // Initialize Servo servoMotor.attach(SERVO_PIN); servoMotor.write(90); delay(1000); Serial.println("Robot Initialized!"); } // ===== MAIN LOOP ===== void loop() { readSensors(); // Periodic obstacle scanning if (millis() - lastScanTime > SCAN_INTERVAL) { checkObstacle(); lastScanTime = millis(); } // Line following logic if (isObstacleDetected()) { stopMotors(); delay(300); avoidObstacle(); } else { followLine(); } // Debug output printStatus(); } // ===== SENSOR READING ===== void readSensors() { leftSensor = analogRead(LEFT_SENSOR); rightSensor = analogRead(RIGHT_SENSOR); } // ===== OBSTACLE DETECTION ===== void checkObstacle() { unsigned int distance = sonar.ping_cm(); if (distance > 0 && distance < OBSTACLE_THRESHOLD) { Serial.print("Obstacle at: "); Serial.print(distance); Serial.println(" cm"); } } bool isObstacleDetected() { unsigned int distance = sonar.ping_cm(); return (distance > 0 && distance < OBSTACLE_THRESHOLD); } // ===== OBSTACLE AVOIDANCE ===== void avoidObstacle() { servoMotor.write(45); // Scan left delay(300); unsigned int leftDist = sonar.ping_cm(); servoMotor.write(135); // Scan right delay(300); unsigned int rightDist = sonar.ping_cm(); servoMotor.write(90); // Center if (rightDist > leftDist) { // More space on right turnRight(); } else { // More space on left turnLeft(); } moveForward(); delay(1000); } // ===== LINE FOLLOWING ===== void followLine() { if (leftSensor < LINE_THRESHOLD && rightSensor < LINE_THRESHOLD) { // Both on line - go straight moveForward(); } else if (leftSensor < LINE_THRESHOLD) { // Left on line, right off - turn left turnLeft(); } else if (rightSensor < LINE_THRESHOLD) { // Right on line, left off - turn right turnRight(); } else { // Both off line - search for line moveForward(); } } // ===== MOTOR CONTROL FUNCTIONS ===== void moveForward() { // Motor 1 (Left) digitalWrite(M1_IN1, HIGH); digitalWrite(M1_IN2, LOW); analogWrite(ENA_PIN, motorSpeed); // Motor 2 (Right) digitalWrite(M2_IN3, HIGH); digitalWrite(M2_IN4, LOW); analogWrite(ENB_PIN, motorSpeed); } void moveBackward() { // Motor 1 (Left) digitalWrite(M1_IN1, LOW); digitalWrite(M1_IN2, HIGH); analogWrite(ENA_PIN, motorSpeed); // Motor 2 (Right) digitalWrite(M2_IN3, LOW); digitalWrite(M2_IN4, HIGH); analogWrite(ENB_PIN, motorSpeed); } void turnLeft() { // Motor 1 (Left) slower digitalWrite(M1_IN1, HIGH); digitalWrite(M1_IN2, LOW); analogWrite(ENA_PIN, 100); // Motor 2 (Right) faster digitalWrite(M2_IN3, HIGH); digitalWrite(M2_IN4, LOW); analogWrite(ENB_PIN, motorSpeed); } void turnRight() { // Motor 1 (Left) faster digitalWrite(M1_IN1, HIGH); digitalWrite(M1_IN2, LOW); analogWrite(ENA_PIN, motorSpeed); // Motor 2 (Right) slower digitalWrite(M2_IN3, HIGH); digitalWrite(M2_IN4, LOW); analogWrite(ENB_PIN, 100); } void stopMotors() { digitalWrite(M1_IN1, LOW); digitalWrite(M1_IN2, LOW); digitalWrite(M2_IN3, LOW); digitalWrite(M2_IN4, LOW); analogWrite(ENA_PIN, 0); analogWrite(ENB_PIN, 0); } // ===== DEBUG OUTPUT ===== void printStatus() { static unsigned long lastPrint = 0; if (millis() - lastPrint > 500) { Serial.print("L:"); Serial.print(leftSensor); Serial.print(" R:"); Serial.print(rightSensor); Serial.print(" D:"); Serial.println(sonar.ping_cm()); lastPrint = millis(); } }
📦 Required Libraries:

1. NewPing (for ultrasonic sensor) - Install via Arduino IDE Library Manager
2. Servo (built-in) - Already included with Arduino IDE

Installation Instructions

  1. Open Arduino IDE
  2. Go to Sketch → Include Library → Manage Libraries
  3. Search "NewPing" by Tim Eckel
  4. Click Install
  5. Copy the code above into Arduino IDE
  6. Select Board: Arduino → Arduino Uno
  7. Select COM Port where Arduino is connected
  8. Click Upload
  9. Open Serial Monitor (9600 baud) to view debug output