App Notes
I use a button to activate a list picker. When the button is clicked I copy the paired devices to a list before I copy to the listpicker. Using a list allows me to check how many paired
devices there are and display a warning if there aren't any. Using a button also gives an easy way to allow the user to disconnect.
Data is contained within start and end markers, I normally use :<" and ">".
I use a timer to check for incoming data and any new data is added to a buffer.
I then check the buffer for the start and end markers. If I have both I know I have a complete data set. I would not normally process data until I get a complete set. I ignore anything not inside the start and end markers
The processIndividualDataElement function handles processing the data. In the example I simply copy the data to a label but you can whatever you like based on the data received.
When receiving a lot of data quickly I find it better to trim the buffer and remove any characters to the left of the start marker (or the first start marker). This is not required when there is not much data or the update is not very frequent.
It is possible that I have more than one data set and so inside the processIncommingData function I loop through the buffer until the buffer does not contain both the start marker and the end marker.
The app can be more robust and I would normally have additional error trapping but I think it can serve as a good foundation for developing a more complex app.
Arduino Sketch
The Arduino sketch also expects data to be enclosed in start
and end markers. The sketch keeps checking serial in (I am using software
serial in the example) and copies it to a receivedChars global variable. Once I
have a complete code I invoke the processData() function.
Circuit.
An Arduino with a Bluetooth module (HC-05/HC-06 or similar). I am using software serial on pins D2 and D3 to talk to the BT module. Hardware serial is used for the serial monitor. Sent data and received data is copied to the serial monitor.
void sendData(byte c){ digitalWrite(13,HIGH); if (c==1) { BTserial.print("<A123B456C789D012>"); Serial.println("OUT - <A123B456C789D012>"); } else if (c==2) { BTserial.print("<A987B654C321D098>"); Serial.println("OUT - <A987B654C321D098>"); } else if (c==3) { BTserial.print("<A111B222C333D444>"); Serial.println("OUT - <A111B222C333D444>"); } delay(50); digitalWrite(13,LOW);}
void formatNumber( unsigned int number, byte digits) { char tempString[10] = "\0"; strcpy(numberString, tempString); // convert an integer into a acsii string base 10 itoa (number, tempString, 10); // create a string of '0' characters to pad the number byte numZeros = digits - strlen(tempString) ; if (numZeros > 0) { for (int i=1; i <= numZeros; i++) { strcat(numberString,"0"); } } strcat(numberString,tempString); }