Reputation: 141
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?
Upvotes: 1
Views: 2438
Reputation: 965
I do this by making my Arduino send 'frames', separated by a 'gap'. It is easy to configure a timeout (at least in Perl it is) for reading data from the serial port. So what I do is:
Allow data being read during the duration of the data frame plus an extra few milliseconds:
[ (number of bytes) × 10 bits × 1000 ms / (baud rate) ] + 100 milliseconds
Then the gap between two values or frames being sent, should be longer than this value.
Upvotes: 0
Reputation: 101149
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.
Upvotes: 2