Skip to content

Instantly share code, notes, and snippets.

@arn-ob
Created March 21, 2018 19:24
Show Gist options
  • Select an option

  • Save arn-ob/7f227a9774060c5cabc7c8638e27862a to your computer and use it in GitHub Desktop.

Select an option

Save arn-ob/7f227a9774060c5cabc7c8638e27862a to your computer and use it in GitHub Desktop.
4 wheel car forward and backward move and Detect obstragle by using Ultra Sonic Sensor And stop the movement
String readvoice;
String readvoicestore;
const int f_trig = 13;
const int f_echo = 12;
const int b_trig = 11;
const int b_echo = 10;
long duration_f;
int distance_f;
long duration_b;
int distance_b;
void setup() {
Serial.begin(9600);
pinMode(f_trig, OUTPUT);
pinMode(f_echo, INPUT);
pinMode(b_trig, OUTPUT);
pinMode(b_echo, INPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
}
//-----------------------------------------------------------------------//
void loop() {
// Serial.println(Serial.read());
while (Serial.available()) { //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read(); //Conduct a serial read
readvoice += c; //build the string- "forward", "reverse", "left" and "right"
}
if (readvoice.length() > 0) {
readvoicestore = readvoice;
}
if (readvoicestore.length() > 0) {
if (readvoicestore == "forward")
{
if (distance_f_() < 20) {
Serial.println("F Stop");
stop();
readvoicestore = "stop";
}
else if (readvoicestore == "stop") {
Serial.println("F Stop Function");
stop();
}
else {
Serial.println("F forword");
forward();
}
}
else if (readvoicestore == "backward")
{
if (distance_b_() < 20) {
Serial.println("B Stop");
stop();
readvoicestore = "stop";
}
else if (readvoicestore == "stop") {
Serial.println("B Stop Function");
stop();
} else {
Serial.println("B backword");
backward();
}
}
readvoice = "";
delay(20);
}
}
int distance_f_() {
digitalWrite(f_trig, LOW);
delayMicroseconds(2);
digitalWrite(f_trig, HIGH);
delayMicroseconds(10);
digitalWrite(f_trig, LOW);
duration_f = pulseIn(f_echo, HIGH);
distance_f = duration_f * 0.034 / 2;
return distance_f;
}
int distance_b_() {
digitalWrite(b_trig, LOW);
delayMicroseconds(2);
digitalWrite(b_trig, HIGH);
delayMicroseconds(10);
digitalWrite(b_trig, LOW);
duration_b = pulseIn(b_echo, HIGH);
distance_b = duration_b * 0.034 / 2;
return distance_b;
}
void forward() {
digitalWrite(7, HIGH);
digitalWrite(9, HIGH);
digitalWrite(6, LOW);
digitalWrite(8, LOW);
delay(20);
}
void backward() {
digitalWrite(6, HIGH);
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
digitalWrite(9, LOW);
delay(20);
}
void stop() {
digitalWrite(6, LOW);
digitalWrite(8, LOW);
digitalWrite(7, LOW);
digitalWrite(9, LOW);
delay(20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment