having some problem with my code.. for the blocked part of sensor motor its okay..but for the "No Obstacles" thing its not doing fine..check my screenshot of the serial monitor..it should keep saying "No Obstacles" and keep moving forward until my car meets a wall or an obstacle and it should reverse itself..but no .. it keeps going between "No Obstacles " and "Blocked"
ALSO, i need help cause my front motor (controls left right and my back motor is for forward and reverse) isn't working for "Blocked"
#include <NewPing.h>2 // don't forget to include the NewPing library.
const int A1A = 6;//define pin 2 for A1A
const int A1B = 7;//define pin 3 for A1B
const int B1A = 8;//define pin 8 for B1A
const int B1B = 9;//define pin 9 for B1B
const int trigPin = 11;
const int echoPin = 12;
long duration;
int distance;
void setup() {
pinMode(B1A,OUTPUT);// define pin as output
pinMode(B1B,OUTPUT);
pinMode(A1A,OUTPUT);
pinMode(A1B,OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
distance = checkDistance();
distance = (duration/2) /29.1;
Serial.print (distance);
Serial.println (" cm");
delay(200);
if (distance >=11){
Serial.println("No Obstacles");
motorA('O');// Turn motor A to LEFT RIGHT
motorB('L');// Turn motor B to FORWARD | BACKWARD
delay(2000);
motorA('O');// Turn motor A OFF
motorB('O');// Turn motor B OFF
}
else if (distance <=10);{
Serial.println("Blocked");
motorA('L');// Turn motor A to
motorB('R');// Turn motor B to
delay(2000);
motorA('O');// Turn motor A OFF
motorB('O');// Turn motor B OFF
}
}
long microsecondsToCentimeters (long microseconds) {
return microseconds / 29 / 2;
}
long checkDistance()
{
/* The following trigPin/echoPin cycle is used to determine the distance of the nearest
object by bouncing soundwaves off it */
//Trigger a HIGH pulse for 2 or more microseconds
//Give a short LOW pulse before sending a HIGH one
digitalWrite (trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite (trigPin, LOW);
//Now, lets read the read the bounced wave
duration = pulseIn(echoPin, HIGH);
//calculate the distance
distance = microsecondsToCentimeters(duration);
return distance;
}
void motorA(char d)
{
if(d =='R'){
digitalWrite(A1A,LOW);
digitalWrite(A1B,HIGH);
}else if (d =='L'){
digitalWrite(A1A,HIGH);
digitalWrite(A1B,LOW);
}
else{
// Turn motor OFF
digitalWrite(A1A,LOW);
digitalWrite(A1B,LOW);
}
}// motorA end
/*
- @motorB
- activation rotation of motor B
- d is the direction
- R = Right
- L = Left
*/
void motorB(char d)
{
if(d =='R'){
digitalWrite(B1A,LOW);
digitalWrite(B1B,HIGH);
}else if(d =='L'){
digitalWrite(B1A,HIGH);
digitalWrite(B1B,LOW);
}else{
// Turn motor OFF
digitalWrite(B1A,LOW);
digitalWrite(B1B,LOW);
}
}
// motorB end