Motors dont switch off when bluetooth disconnects. Any advice

Hi there.

I am having problems with my sketch. When I disconnect my android app or the bluetooth connection my motors go to full speed without turning of. I have switch the battery of for it to stop. Does anyone have any ideas for me please. Here is my sketch and thanks for the help.

#define MOTOR_PIN 9

int _pulseTime = 0; //microseconds
boolean _highSpeed = true;

void setup()
{
Serial.begin(9600);
pinMode(9, OUTPUT);
digitalWrite(9, LOW);
Serial.println("Enter 0-8 to adjust motor speed.");
Serial.println("Enter h or l to change the speed range.");
}

void loop()
{
static int timing[] = {1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000 };

// Pulse servo
digitalWrite(9, HIGH);
delayMicroseconds(_pulseTime);
digitalWrite(9, LOW);

int incomingByte = 0;
if (Serial.available() > 0)
{
incomingByte = Serial.read();

int index = incomingByte - 48;
if (index >= 0 && index < sizeof(timing) / sizeof(int))
{
setTimingParams(timing[index]);
Serial.print("Throttle: ");
Serial.print((_pulseTime - 1100) / 8);
Serial.println("%");
}
else
{
if (incomingByte == 'h')
{
_highSpeed = true;
}
else if (incomingByte == 'l')
{
_highSpeed = false;
}
}
}

// OFF time
delay(20);
}

void setTimingParams(int newPulseTimeVal) {
if (_highSpeed) {
_pulseTime = newPulseTimeVal;
}
else {
_pulseTime = 1025 + (newPulseTimeVal / 10);
}
}

I haven't the faintest ideas about what you are doing , and even less about the bluetooth you are using, but, if you check the bluetooth data sheet, you may find there is a pin available that changes, and stays changed, on connect/disconnect. This might be used as an overall control for the motors.

How do you know that I have stopped reading your posts here?

What you are asking for is for your motor to stop running when I quit reading your posts.

The ONLY way you will know that is if I reply to every post you make, within a certain time frame after you make the post.

What YOU have to do is keep track of the time that you last received data from the app on the other end of the bluetooth connection, and, if it has been too long, stop the motors yourself.

That means, of course, that the app on the other end needs to send data at regular intervals, even if it has nothing new to say - a heartbeat, as it were, just to let you know that it is still alive.

I agree with the system @PaulS is proposing. I use it with my radio controlled trains. Normally a message is sent about 10 times per second and if a whole second goes by without any message being received the locomotive stops.

...R

Great, thanks for your answers. Will try my best to solve the problem