Hi everyone, so for my schoolproject I am making an "rc-car" which you can control on your smartphone with an app I've made. The only problem I'm having is that i can only drive in small shocks. This is because my delay is set to '10'. But does anyone have a better approach on how to control the vehicle so it keeps driving. I could also add a stop button, but i'd rather do it in another way
#include <SoftwareSerial.h>
char t = '\0';
int trigPin = 6; // TRIG pin
int echoPin = 7; // ECHO pin
int input1 = 9;
int input2 = 8;
int input3 = 2;
int input4 = 3;
const byte rxPin = 5;
const byte txPin = 4;
SoftwareSerial mySerial(rxPin, txPin);
float duration_us, distance_cm;
bool distance = false;
void setup() {
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
pinMode(2, OUTPUT); //left motors forward
pinMode(3, OUTPUT); //left motors reverse
pinMode(8, OUTPUT); //right motors forward
pinMode(9, OUTPUT); //right motors reverse
pinMode(10, OUTPUT);
pinMode(11, OUTPUT); //Led
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
mySerial.begin(9600);
Serial.begin(9600);
pinMode(trigPin, OUTPUT); // configure the trigger pin to output mode
pinMode(echoPin, INPUT); // configure the echo pin to input mode
}
void loop() {
// If any data is available at the Bluetooth Serial Port
if (mySerial.available()) {
t = mySerial.read();
Serial.write(t);
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration_us = pulseIn(echoPin, HIGH); // measure duration of pulse from ECHO pin
distance_cm = 0.017218 * duration_us; // calculate the distance
if (distance_cm >= 10)
distance = true;
else
distance = false;
if (t == 'F') { //move forward
do{
Serial.println("Fout");
digitalWrite(input3, HIGH);
digitalWrite(input4, LOW);
}while(t == 'F');
}
else if (t == 'B') { //move reverse
do{
digitalWrite(input3, LOW);
digitalWrite(input4, HIGH);
t = mySerial.read();
}while(t == 'B');
}
else if (t == 'R') { //turn right (left side motors rotate in forward direction, right side motors doesn't rotate)
digitalWrite(input1, HIGH);
digitalWrite(input2, LOW);
}
else if (t == 'L') { //turn left (right side motors rotate in forward direction, left side motors doesn't rotate)
digitalWrite(input1, LOW);
digitalWrite(input2, HIGH);
}
else if (t == '1') { //turn led on or off)
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
digitalWrite(13, HIGH);
}
else if (t == '0') {
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
digitalWrite(13, LOW);
}
else if (t == 'S' || distance == true) { //STOP (all motors stop)
digitalWrite(input1, LOW);
digitalWrite(input2, LOW);
digitalWrite(input3, LOW);
digitalWrite(input4, LOW);
}
delay(10);
}