If you want an Edge Avoiding Robot using only Arduino + L298N + HC-SR04 Ultrasonic Sensor, mount the ultrasonic sensor facing downward at the front edge of the robot.
Working
- Normal floor distance: 3–10 cm (depending on mounting height).
- When the robot reaches a table edge, the ultrasonic sensor sees a much larger distance (or no echo).
- Robot moves backward and turns away from the edge.
Connections
HC-SR04
| HC-SR04 | Arduino |
|---|---|
| VCC | 5V |
| GND | GND |
| TRIG | D9 |
| ECHO | D10 |
L298N
| L298N | Arduino |
|---|---|
| IN1 | D2 |
| IN2 | D3 |
| IN3 | D4 |
| IN4 | D5 |
Keep ENA and ENB jumpers ON.
Arduino Code
#define TRIG 9
#define ECHO 10
#define IN1 2
#define IN2 3
#define IN3 4
#define IN4 5
long duration;
int distance;
void setup()
{
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
Serial.begin(9600);
}
void loop()
{
distance = getDistance();
Serial.print("Distance: ");
Serial.println(distance);
// Floor detected
if(distance < 15)
{
forward();
}
// Edge detected
else
{
stopRobot();
delay(200);
backward();
delay(600);
stopRobot();
delay(200);
rightTurn();
delay(600);
stopRobot();
delay(200);
}
}
int getDistance()
{
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
duration = pulseIn(ECHO, HIGH, 30000);
if(duration == 0)
return 100;
return duration * 0.034 / 2;
}
void forward()
{
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
void backward()
{
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void rightTurn()
{
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void stopRobot()
{
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}
Important
- Point the HC-SR04 downward toward the floor, not forward.
- Measure the distance from the sensor to the floor and adjust this line if needed:
if(distance < 15)
For example:
- Sensor height = 5 cm → use 8–10 cm threshold.
- Sensor height = 10 cm → use 12–15 cm threshold.
This method works, but IR sensors are usually more reliable for edge-avoiding robots. Ultrasonic edge detection requires careful mounting and threshold tuning.