Obstacle avoiding robot with Arduino code
Updated: Aug 4, 2023
To make an obstacle avoiding robot, watch the step by step video on my youtube channel: https://youtu.be/GJ6XHrs9Lf0
Arduino code:
const int trigPin1 = 11;
const int echoPin1 = 10;
const int m11 =9; // M1a
const int m12 =8; // M1b
const int m21 =7; // M2a
const int m22 =6; // M2b
const int M11 =5; // M1a
const int M12 =4; // M1b
const int M21 =3; // M2a
const int M22 =2; // M2b
void setup()
{
Serial.begin(9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(m11, OUTPUT);
pinMode(m12, OUTPUT);
pinMode(m21, OUTPUT);
pinMode(m22, OUTPUT);
pinMode(M11, OUTPUT);
pinMode(M12, OUTPUT);
pinMode(M21, OUTPUT);
pinMode(M22, OUTPUT);
}
long duration, distance;
void loop()
{
digitalWrite(trigPin1, LOW);
delayMicroseconds(5);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(5);
digitalWrite(trigPin1, LOW);
duration = pulseIn(echoPin1, HIGH);
distance = (duration/2) / 29.1;
if(distance<10) //MOVE LEFT
{
digitalWrite(m11, LOW);
digitalWrite(m12, HIGH);
digitalWrite(m21, HIGH);
digitalWrite(m22, LOW);
digitalWrite(M11, LOW);
digitalWrite(M12, HIGH);
digitalWrite(M21, HIGH);
digitalWrite(M22, LOW);
}
else //MOVE STRAIGHT
{
digitalWrite(m11, HIGH);
digitalWrite(m12, LOW);
digitalWrite(m21, HIGH);
digitalWrite(m22, LOW);
digitalWrite(M11, HIGH);
digitalWrite(M12, LOW);
digitalWrite(M21, HIGH);
digitalWrite(M22, LOW);
}
}
Comments