Cirkit Designer LogoCirkit DesignerYour all-in-one circuit design IDE Launch Cirkit Designer App

Arduino-Controlled Ultrasonic Obstacle Avoidance Robot with L298N Motor Driver

View and Edit Project In Cirkit DesignerImage of Arduino-Controlled Ultrasonic Obstacle Avoidance Robot with L298N Motor Driver

Circuit Documentation

Summary

This circuit is designed to control two DC motors using an L298N motor driver module, with an Arduino UNO as the central microcontroller. The circuit also includes an HC-SR04 ultrasonic sensor for distance measurement. A 9V battery is used to power the motor driver, which in turn powers the motors and the Arduino UNO.

Component List

Arduino UNO

HC-SR04 Ultrasonic Sensor

L298N DC Motor Driver

Motor Amarillo Motorreductor Hobby (x2)

9V Battery

Wiring Details

Arduino UNO

HC-SR04 Ultrasonic Sensor

L298N DC Motor Driver

Motor Amarillo Motorreductor Hobby

9V Battery

Documented Code

#define Trig 8
#define Echo 9

const int in21 = 4;    // L298N-2 pin 4
const int in22 = 5;    // L298N-2 pin 5
const int in23 = 6;    // L298N-2 pin 6
const int in24 = 7;    // L298N-2 pin 7
const int enA = 10;    // L298N-2 pin 10
const int enB = 11;    // L298N-2 pin 11

void setup() 
{  
  pinMode(Trig, OUTPUT); // Set Trig as output
  pinMode(Echo, INPUT);  // Set Echo as input
  
  // Set L298N control pins as outputs
  pinMode(in21, OUTPUT);
  pinMode(in22, OUTPUT);
  pinMode(in23, OUTPUT);
  pinMode(in24, OUTPUT);
} 

unsigned int impulseTime=0; 
unsigned int distance_sm=0; 

void loop() 
{  
  // Generate ultrasonic pulse
  digitalWrite(Trig, HIGH); 
  delayMicroseconds(10); // 10 microseconds
  digitalWrite(Trig, LOW);
  
  // Measure the length of the echo pulse
  impulseTime = pulseIn(Echo, HIGH); 
  distance_sm = impulseTime / 58; // Convert to centimeters

  // If the distance is greater than 25 centimeters
  if (distance_sm > 25) 
  {     
      // Move motors forward
      digitalWrite(in21, LOW);
      digitalWrite(in22, HIGH);
      analogWrite(enA, 60);

      analogWrite(enB, 60);
      digitalWrite(in23, HIGH);
      digitalWrite(in24, LOW);
  }  
  else 
  {   
      // Move motors backward
      digitalWrite(in21, HIGH);
      digitalWrite(in22, LOW);

      analogWrite(enA, 100);

      analogWrite(enB, 100);
      
      digitalWrite(in23, HIGH);
      digitalWrite(in24, LOW); 
      delay(1100); // Adjust time for turning if necessary
  }   

  delay(50); // Short delay before next loop
}

This code is designed to control the motors connected to the L298N motor driver based on the distance measured by the HC-SR04 ultrasonic sensor. If the measured distance is greater than 25 centimeters, the motors will move forward. If the distance is less than or equal to 25 centimeters, the motors will move backward for a short period to avoid obstacles.