This is the code of the app:
private class ConnectedThread{
private final BluetoothSocket socket;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket ss){
socket = ss;
OutputStream OS = null;
try{
OS = socket.getOutputStream();
} catch (IOException e){}
outputStream = OS;
}
public void write(byte[] bytes){
try{
outputStream.write(bytes);
Log.d("Data send:", bytes.toString());
} catch (IOException e) {}
}
public void cancel(){
try{
socket.close();
} catch (IOException e) {}
}
}
The method write(byte[] bytes) its called when an option is selected, the codes are integers between 00010-34000
This method creates the message:
public void onCodeToSend(short code) {
byte [] buff = intToBytes(code);
int newDim = buff.length + 1;
char c = '*';
buff = Arrays.copyOf(buff, newDim);
buff[newDim - 1] = (byte) c;
if(buff != null) connectThread.connectedThread.write(buff);
else Toast.makeText(this.getBaseContext(), "Buffer null", Toast.LENGTH_SHORT);
}
public byte[] intToBytes(short x){
return ByteBuffer.allocate(Short.BYTES).putShort(x).array();
}
On the arduino i have this functions:
Main loop:
void loop() {
if(Serial.available()){
uint16_t code;
code = readData();
delay(25);
clean_buffer();
delay(25);
switch(code/10000){
case 1:
manual(code);
break;
case 0:
break;
case 2:
automatico(code);
break;
default:
//Serial.println("Error");
clean_buffer();
break;
}
clean_buffer();
}
delay(25);
}
Function used to read the data from the BT:
uint16_t readData(){
char endMarker = '*';
byte bytes[2];
int i = 0;
char c;
boolean newData = false;
while(Serial.available() > 0 && !newData){
c = Serial.read();
delay(50);
if(c != endMarker){
bytes[i] = (byte)c;
i++;
}
else{
newData = true;
}
}
uint16_t val = byteToLong(bytes[0], bytes[1]);
return val;
}
uint16_t byteToLong(byte byte1, byte byte2){
return byte1 << 8
| byte2;
}
Then i have code for control the stips, in some sequences that are in a infinite loop the input is checked every iteration:
while(true){
do_strip_control()
if(Serial.available())
return_to_main;
}
The problem becomes when I close the app or a time is elapsed and the sync is lost, some type of control message is sent.