1

I am trying to use an ultrasonic sensor to stop a tiny voice-controlled car but I can't get it to work. once the motor starts moving it doesn't stop I'm trying to make the car stop moving even though it is already in motion. I need help writing a proper if statement or while loop to make the motor stop when there is an obstacle in its path.

#include <SoftwareSerial.h>

SoftwareSerial BT(0, 1); //TX, RX respetively
String readvoice;
int IN1= 3;
int IN2= 4;
int IN3= 5;
int IN4= 6;
int trigpin= 12;
int echopin= 11;
int pingTraveltime;
void setup() {
BT.begin(9600);
Serial.begin(9600);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(trigpin, OUTPUT);
pinMode(trigpin, OUTPUT);

}
//-----------------------------------------------------------------------//
void loop() {
while (BT.available()){ //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = BT.read(); //Conduct a serial read
readvoice += c; //build the string- "forward", "reverse", "left" and "right"
digitalWrite(trigpin,LOW);
delayMicroseconds(10);
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);
pingTraveltime=pulseIn(echopin,HIGH);
Serial.println(pingTraveltime);
}
if (readvoice.length() > 0) {
Serial.println(readvoice);

if(readvoice == "*forward#")
{
while(pingTraveltime>500){
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);
}
}

else if(readvoice == "*back#" )
{
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN4,HIGH);
}

else if (readvoice == "*left#")
{
digitalWrite (IN1,HIGH);
digitalWrite (IN2,LOW);
digitalWrite (IN3,LOW);
digitalWrite (IN4,LOW);

}

else if ( readvoice == "*right#")
{
digitalWrite (IN1, LOW);
digitalWrite (IN2, HIGH);
digitalWrite (IN3, LOW);
digitalWrite (IN4, LOW);

}

else if (readvoice == "*stop#")
{
digitalWrite (IN1, LOW);
digitalWrite (IN2, LOW);
digitalWrite (IN3, LOW);
digitalWrite (IN4, LOW);
}

readvoice="";}} //Reset the variable
1
  • first thing to do, format the code properly ... please use correct indent levels for each block ... you can press ctrl-T in the Arduino IDE for auto format
    – jsotola
    Jun 14 at 4:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.