I have a project to control an RC boat via Bluetooth. Everything is working fine using the code below but I would like something in there to stop the motors if communications between the arduino and the tablet are lost.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9); // RX, TX
char data = 0; //Variable for storing received data
const int lm1=7;
const int lm2=6;
const int rm1=5;
const int rm2=4;
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set up Serial library at 9600 bps
mySerial.begin(9600); // Set the data rate for the SoftwareSerial port
Serial.println("PC Comms Up"); // prints to serial port to confirm communications are up.
pinMode(lm1,OUTPUT);
pinMode(lm2,OUTPUT);
pinMode(rm1,OUTPUT);
pinMode(rm2,OUTPUT);
}
void loop() // run over and over again
{
if(mySerial.available() > 0) // Send data only when you receive data:
{
data = mySerial.read(); //Read the incoming data & store into data
Serial.println(data); //Print Value inside data in Serial monitor
if(data=='F'){
front();
}else if(data=='B'){
back();
}else if(data=='L'){
left();
}else if(data=='R'){
right();
}else if(data=='S'){
Break();
}
}
}
void front(){
Serial.println("Forward Move");
digitalWrite(lm1,HIGH);
digitalWrite(lm2,LOW);
digitalWrite(rm1,HIGH);
digitalWrite(rm2,LOW);
}
void back(){
Serial.println("Back Move");
digitalWrite(lm1,LOW);
digitalWrite(lm2,HIGH);
digitalWrite(rm1,LOW);
digitalWrite(rm2,HIGH);
}
void left(){
Serial.println("Left Move");
digitalWrite(lm1,LOW);
digitalWrite(lm2,HIGH);
digitalWrite(rm1,HIGH);
digitalWrite(rm2,LOW);
}
void right(){
Serial.println("Right Move");
digitalWrite(lm2,LOW);
digitalWrite(lm1,HIGH);
digitalWrite(rm2,HIGH);
digitalWrite(rm1,LOW);
}
void Break(){
Serial.println("Break");
digitalWrite(lm2,LOW);
digitalWrite(lm1,LOW);
digitalWrite(rm1,LOW);
digitalWrite(rm2,LOW);
}
I tried adding else Break(); just before the } preceding the void Front and it causes the motors to just spin for a second and then stop.