Search This Blog

Friday, 21 April 2023

obstacle avoidance robot using arduino

 Here is the code for making a obstacle avoidance robot using :-

1) l298n motor driver 
2) arduino (any)
3)servo  motor (optional)
4) 2 or 4 dc motors and wheels
5)jumper cables if (needed )
6) breadboard if (needed) 



// Motor driver pins

int ENA = 3; int ENB = 5; int IN1 = 2; int IN2 = 4; int IN3 = 6; int IN4 = 7; // Servo pin int servoPin = 9; // Ultrasonic sensor pins int trigPin = 10; int echoPin = 11; // Distance variables long duration; int distance; void setup() { // Set motor driver pins as outputs pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); // Set servo pin as output pinMode(servoPin, OUTPUT); // Set ultrasonic sensor pins pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); // Start serial communication Serial.begin(9600); } void loop() { // Rotate servo to scan area for obstacles for (int i = 0; i <= 180; i += 5) { int angle = map(i, 0, 180, 0, 179); digitalWrite(servoPin, HIGH); delayMicroseconds(500 + angle * 5); digitalWrite(servoPin, LOW); delay(30); duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; if (distance < 30) { // If obstacle detected, stop and turn digitalWrite(ENA, LOW); digitalWrite(ENB, LOW); digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); delay(500); digitalWrite(ENA, HIGH); digitalWrite(ENB, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); delay(1000); } } // Move forward if no obstacles detected digitalWrite(ENA, HIGH); digitalWrite(ENB, HIGH); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); delay(500); }

This code uses a servo motor to scan the area for obstacles and an ultrasonic sensor to measure the distance to any obstacles. If an obstacle is detected within 30 cm, the robot stops and turns for 1 second before continuing to move forward. If no obstacles are detected, the robot moves forward. The L298N motor driver is used to control the two motors.





No comments:

Post a Comment

interfacing ph sensor with arduino

You will need to connect the pH sensor to the Arduino board and configure the pins accordingly. Refer to the documentation of your pH se...