Created
January 13, 2024 02:28
-
-
Save dsvakola/d9aa0f8f797c38285ff14d116513683e to your computer and use it in GitHub Desktop.
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 <AFMotor.h> // library file included | |
/**** global declaration ****/ | |
AF_DCMotor RM(3); // Right dc motor connected to M3 socket | |
AF_DCMotor LM(4); // Left dc motor connected to M4 socket | |
int trigger = 8; // for US sensor | |
int echo = 9; // for US sensor | |
float time = 0; // for US sensor | |
float distance = 0; // for US sensor | |
void setup() | |
{ | |
// set initial speed of motors | |
LM.setSpeed(100); // 0 = stop, 255 = max speed | |
RM.setSpeed(100); // 0 = stop, 255 = max speed | |
// set US sensor pins | |
pinMode(trigger,OUTPUT); | |
pinMode(echo,INPUT); | |
delay(7000); | |
} | |
void loop() | |
{ | |
// generate a random number, either 0 or 1 | |
int x = random(2); | |
digitalWrite(trigger,LOW); | |
delayMicroseconds(1); | |
digitalWrite(trigger,HIGH); | |
delayMicroseconds(1); | |
digitalWrite(trigger,LOW); | |
delayMicroseconds(1); | |
// echo received | |
time = pulseIn(echo,HIGH); | |
// formula to calculate the distance | |
// distance is calculated in cm | |
distance = time * 0.034 / 2; | |
/***** Control the Trolley *****/ | |
if(distance < 10) // obstacle detected | |
{ | |
// stop | |
LM.run(RELEASE); | |
RM.run(RELEASE); | |
delay(2000); | |
// go backward | |
LM.setSpeed(200); | |
RM.setSpeed(200); | |
LM.run(BACKWARD); | |
RM.run(BACKWARD); | |
delay(900); | |
// stop | |
LM.run(RELEASE); | |
RM.run(RELEASE); | |
delay(2000); | |
// for random turn, either left turn or right turn | |
if(x == 0) | |
{ | |
// power right turn | |
LM.setSpeed(110); | |
RM.setSpeed(110); | |
LM.run(FORWARD); | |
RM.run(BACKWARD); | |
delay(300); | |
} | |
else | |
{ | |
// power left turn | |
LM.setSpeed(110); | |
RM.setSpeed(110); | |
LM.run(BACKWARD); | |
RM.run(FORWARD); | |
delay(300); | |
} | |
// stop | |
LM.run(RELEASE); | |
RM.run(RELEASE); | |
delay(2000); | |
} | |
else | |
{ | |
// go forward | |
LM.setSpeed(100); | |
RM.setSpeed(100); | |
LM.run(FORWARD); | |
RM.run(FORWARD); | |
} | |
} // loop closed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment