I am trying to send integers 0 through 10 from my Arduino Uno to my Android device. However, the Arduino is not sending the integers separately, but rather it is sending it as a cluster (sometimes 2 at a time). I want to be able to send an integer every 5 milliseconds and not delay any longer than that. Any ideas?
Arduino code:
#include <SoftwareSerial.h>
const int RX_PIN = 8;
const int TX_PIN = 9;
SoftwareSerial bluetooth(RX_PIN, TX_PIN);
char commandChar;
void setup (){
bluetooth.begin (9600);
Serial.begin(9600);
}
void loop () {
if(bluetooth.available()){
commandChar = bluetooth.read();
switch(commandChar){
case '*':
for(int i = 0; i < 11; i++){
bluetooth.print(i);
delay(5);
}
break;
}
}
}
Android code:
public void run() {
initializeConnection();
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
while (true) {
try {
if(mmSocket!=null) {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
Log.e("Received Message ", readMessage);
}
}
} catch (IOException e) {
Log.e("ERROR ", "reading from btInputStream");
break;
}
}
}
Android Monitor/Console output:
08-18 19:46:32.319 6720-6749/? E/Received Message: 0
08-18 19:46:32.324 6720-6749/? E/Received Message: 1
08-18 19:46:32.324 6720-6749/? E/Received Message: 23
08-18 19:46:32.324 6720-6749/? E/Received Message: 4
08-18 19:46:32.379 6720-6749/? E/Received Message: 56
08-18 19:46:32.379 6720-6749/? E/Received Message: 78
08-18 19:46:32.379 6720-6749/? E/Received Message: 91
08-18 19:46:32.384 6720-6749/? E/Received Message: 0
It seems that the serial communication is working as stream (not datagram) and isn't keeping any data boundary.
Therefore, it seems you should add data separator (for example: newline) to your sending data and process it in the receiver (for example: use
BufferedReader
) to keep the data boundary.