I am trying to read serial data from an Arduino bluetooth module.I am testing a simple receive loop, but I seem to get garbage data. My arduino code is
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(6, 7); // RX | TX
String my_string;
void setup() {
Serial.begin(9600);
BTSerial.begin(9600);
}
void loop() {
while (BTSerial.available())
{
char c = BTSerial.read();
my_string += c;
delay(2);
}
delay(500);
BTSerial.write("shot\r\n");
}
My handler on Android is:
class serial_handler extends Handler {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
Log.d("OP", "CHAR:"+ sbprint);
}
Log.d("OP", "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
But I see garbage received on the serial input on Android:
...String:�cn�p`t�ch`d�
sCh�cH�p`dshoD����cH�ptshod1�
s
Chc�s�rByte:1...
I am not sure where is additonal garbage serial data is coming from. Is my arduino loop set up right?