felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.8k stars 585 forks source link

Receiving empty data from arduino leonardo #231

Closed uklertis closed 5 years ago

uklertis commented 5 years ago

Hi I have a raspi 3 model b that running Android things as OS. I want to read serial data from USB but I'm getting only empty value and I tried to read data with NodeJS and I read it but with this library I'm getting only empty string. Here is my arduino sketch: void setup() { // put your setup code here, to run once: Serial.begin(115200); }

void loop() { // put your main code here, to run repeatedly: Serial.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); delay(1000); }

and my Java code

private UsbSerialInterface.UsbReadCallback callback = new UsbSerialInterface.UsbReadCallback() { @Override public void onReceivedData(byte[] data) { try { String dataUtf8 = new String(data, "UTF-8"); Log.i(TAG, "Data: " + dataUtf8); buffer += dataUtf8; int index; while ((index = buffer.indexOf('\n')) != -1) { final String dataStr = buffer.substring(0, index + 1).trim(); buffer = buffer.length() == index ? "" : buffer.substring(index + 1); runOnUiThread(new Runnable() { @Override public void run() { onSerialDataReceived(dataStr); } }); } } catch (UnsupportedEncodingException e) { Log.e(TAG, "Error receiving USB data", e); } } };

When I printed data I got this result: [B@957bff4 but if I try to convert it to string like String dataUtf8 = new String(data, "UTF-8"); return empty string. any help please?

felHR85 commented 5 years ago

@uklertis [B@957bff4 that's the reference of the byte[] object. Does both ends have the same baud rate? it doesnt seem you are sending \n in your Arduino code.

uklertis commented 5 years ago

I'm so sorry for the delay for my answer. I'm pretty sure that I set the baud rates correctly and I'm using println function to send serial data which means I'm already sending \n in my Arduino code. I sent data with write and print functions like this: Serial.print("Hi There\n"); Serial.write("Hi There\n"); but no luck. You have any idea what is the problem?

uklertis commented 5 years ago

I solved the problem by using this library