I have a simple sonar arduino project so that it prints the distance every second. I have implemented an android app using UsbSerial to communicate with my arduino. So far so good, I am able to receive data and the data I receive is correct, but the problem is that the values are sometimes not properly sent. Here is the sample output I receive:
data: 7
data: 1
data:
data: 71
and here is the code that generates output:
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] arg0)
{
try {
String data = new String(arg0, "UTF-8");
System.out.println("data: " + data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
So in my opinion there is 2 problems here:
- Lines 1 & 2 must be just one line with the value of
71
- Line 3 should not exists as my application is listening
onReceivedData
and arduino always send something.
Any help would be much appreciated.
I have found a solution for the issue. by reading this link I noticed that I need to do some manipulation on the data I receive in the
onReceivedData
method. So I changed themCallBack
as follow:and here is the other methods I added:
And also I modified the Arduino code and added character
A
to the beginning of the serial output. This solves the issue, however I think this is not the best practice. I think the UsbSerial library should provide better output handling( or maybe I am wrong and this is the nature of working with serial communication ).