Created
February 14, 2024 23:22
-
-
Save Ajak58a/064cd21076d82b9911cdad09fe79c735 to your computer and use it in GitHub Desktop.
Object following robot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> | |
#define udm_trig 7 | |
#define udm_echo 6 | |
#define RightMotorPin1 2 | |
#define RightMotorPin2 3 | |
#define LeftMotorPin1 4 | |
#define LeftMotorPin2 5 | |
#define soundpin 12 | |
Servo sensor_servo; | |
int angle,follow_object_flag=0; | |
long duration, object_distance; | |
void setup() | |
{ | |
sensor_servo.attach(10); | |
pinMode(udm_trig,OUTPUT); | |
pinMode(udm_echo,INPUT); | |
pinMode(2,OUTPUT); | |
pinMode(3,OUTPUT); | |
pinMode(4,OUTPUT); | |
pinMode(5,OUTPUT); | |
pinMode(12,OUTPUT); | |
digitalWrite(2,LOW); | |
digitalWrite(3,LOW); | |
digitalWrite(4,LOW); | |
digitalWrite(5,LOW); | |
digitalWrite(12,LOW); | |
sensor_servo.write(90); | |
delay(2000); | |
} | |
void turn_left() | |
{ | |
digitalWrite(RightMotorPin1, HIGH); | |
digitalWrite(RightMotorPin2, LOW); | |
delay(2000); | |
digitalWrite(RightMotorPin1, LOW); | |
} | |
void turn_right() | |
{ | |
digitalWrite(LeftMotorPin1, HIGH); | |
digitalWrite(LeftMotorPin2, LOW); | |
delay(2000); | |
digitalWrite(LeftMotorPin1, LOW); | |
} | |
void move_forward() | |
{ | |
digitalWrite(RightMotorPin1, HIGH); | |
digitalWrite(RightMotorPin2, LOW); | |
digitalWrite(LeftMotorPin1, HIGH); | |
digitalWrite(LeftMotorPin2, LOW); | |
} | |
void stop_robot() | |
{ | |
digitalWrite(RightMotorPin1, LOW); | |
digitalWrite(RightMotorPin2, LOW); | |
digitalWrite(LeftMotorPin1, LOW); | |
digitalWrite(LeftMotorPin2, LOW); | |
} | |
void follow_object() | |
{ | |
digitalWrite(udm_trig,HIGH); | |
delayMicroseconds(10); | |
digitalWrite(udm_trig,HIGH); | |
duration = pulseIn(udm_echo, HIGH); | |
object_distance = duration/29/2; | |
if(object_distance>30) follow_object_flag=1; | |
} | |
void loop() | |
{ | |
for(angle=45;angle<135;angle+=5) | |
{ | |
sensor_servo.write(angle); | |
digitalWrite(udm_trig,HIGH); | |
delayMicroseconds(10); | |
digitalWrite(udm_trig,HIGH); | |
duration = pulseIn(udm_echo, HIGH); | |
object_distance = duration/29/2; | |
if(object_distance<30) | |
{ | |
sensor_servo.write(90); | |
if(angle<90) turn_left(); | |
else if(angle>90) turn_right(); | |
digitalWrite(soundpin,HIGH); | |
move_forward(); | |
while(follow_object_flag==0) | |
{ | |
follow_object(); | |
delay(200); | |
} | |
stop_robot(); | |
digitalWrite(soundpin,LOW); | |
follow_object_flag=0; | |
} | |
delay(100); | |
} | |
for(angle=135;angle>35;angle-=5) | |
{ | |
sensor_servo.write(angle); | |
delay(20); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment