I'm trying to interact with my Arduino Uno from my Android tablet running 4.0.3 and got everything working using the Android USB Host API, which means I can send data over USB to the board and read it there via Serial.read()
successfully.
Now I'm trying to implement a feedback functionality, which means the other way around, sending from the Arduino Uno and reading on the tablet. This works also quite well using Serial.write()
, but I got a little problem: Sometimes, there are no bytes transferred and some other times, only some of them, so the content I'm sending is cut in half. How do I fix this?
I'm asssuming the Serial port has some issues sending all of the data. Should I perhaps change the baud-rate which is currently at 9600?
Here's the code on the Android side:
byte[]data = new byte[1024]; //Bigger size just to make sure...
int returnLen = conn.bulkTransfer(epIN,data,data.length,500); //epIN is the`
On the Arduino side a simple
Serial.write(5);
is used.
The read()
behavior you are seeing is working as intended: sometimes, fewer bytes will be available than the amount you want. It's very similar to standard POSIX read() syscall behavior:
"It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now [..]"
Your application needs to handle this possibility. A common technique is to keep track of how many bytes you have read, and perform successive read()
calls, accumulating bytes until you have the number desired.
Finally, consider using usb-serial-for-android, an open source library implementing FTDI and CDC (Arduino) USB drivers. Though it doesn't specifically deal with this application-level issue, it may save you trouble elsewhere, and has an active mailing list.