I’m trying to read serial data from my Arduino using Java. I have followed the tutorial Arduino and Java.
So far I have it working except, I’m not reading the whole of the serial data at once. For example, the Arduino should be sending 0.71, and I read in a 0 then a .71 or some other combination. Sometimes I read it in fine, but more often than not, the data is broken up.
I have a hunch that if I changed the data type of what I am sending to a byte, my program would be okay, however I need float precision in the data I am transferring. How do I fix this problem?
Serial protocols such as the one used for serial over USB are byte oriented, not packet oriented. As such, there’s no guarantee that a read will return the entire ‘message’ sent by the other end, or just part of it, as you’re observing, because there’s no concept of message or packet.
Instead, you need to delimit your messages in some way – such as by appending a newline – or preprend messages with a length field, so you know how many bytes to read.