Here is the loop from my Bluetooth program. The sender is the serial Bluetooth terminal app on my Android tablet.
The code watches for an incoming byte from the sender. I matters not the value, it just warns the Arduino that data is forthcoming. The Arduino program clears the serial buffer and exits the mode that controls the display (calls show()) and sends a message to the sender to say that it is ready for data. The sender then sends data and the Arduino reads each packet and acts on it. After the last data packet a <d>
is sent to tell the Arduino that all data has been sent. When the Arduino receives the <d>
it sets the mode back to controlling the LED strip (calling show(). The serial reading and parsing is done with code from the serial input basics tutorial.
Here is the loop() to show how I switch modes on incoming serial data.
void loop()
{
if (mode == 0) // show mode
{
showMiles();
showDP(dpColor);
if (bt.available()) // if a character has come in
{
while (bt.available())
{
// read and throw away alert character
bt.read(); // clear bt buffer
}
mode = 1; // go to the serial input mode
}
}
else if (mode == 1) // read serial mode
{
if (setupMsg == 0) // send setup message if it hasn't been sent
// tells the sender that the Arduino is ready for real data
{
Serial.println("Entered set up mode");
bt.println("Entered set up mode");
setupMsg = 1; // setup message sent
}
recvWithStartEndMarkers(); // get packet
if (newData == true) // new packet recieved
{
parseData();
// the parseData function will set mode back to 0
// when all serial is received and processed and <d> is sent
}
}
}