Course Content
📘 MODULE 9 – Automatic Dustbin
0/1
📘 MODULE 10 – Obstacle Avoiding Robot
0/1
📘 MODULE 11 – Edge Avoiding Robot
0/1
Arduino Hands-On Programming and Robotics Course

Connections

Ultrasonic Sensor (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 connected on the L298N board.


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.print(distance);
  Serial.println(" cm");

  if(distance > 20)
  {
    forward();
  }
  else
  {
    stopRobot();
    delay(300);

    backward();
    delay(500);

    stopRobot();
    delay(300);

    rightTurn();
    delay(600);

    stopRobot();
    delay(300);
  }
}

int getDistance()
{
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);

  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIG, LOW);

  duration = pulseIn(ECHO, HIGH);

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

This code works with:

  • Arduino Uno
  • L298N (ENA & ENB jumpers ON)
  • HC-SR04 Ultrasonic Sensor
  • 2 DC Motors

The robot will move forward and automatically turn right when an obstacle is detected within 20 cm.

Scroll to Top