I'm trying to do some fairly simple serial communication and have things partially working, but am pretty confused about a couple results I'm getting.
For a little background, I'm using an Arduino Mega 2560 to try to communicate with a Dynamixel servo (MX-64) over TTL (half-duplex, asynchronous) with Tx1 and Rx1. Basically I construct some byte arrays as instructions, send them over to the servo (with Serial1.write()
), and then read back a reply. I've actually gotten it to work pretty well if I use Serial1.readBytes()
, specifying the length of the buffer (number of bytes I'm expecting). I'm also reading back what I originally sent (first) as well as the response (second), since I have Tx1 and Rx1 tied together (required in my setup because this servo only has one data wire).
However I don't understand the difference between Serial.readBytes()
and Serial.read()
. If I do Serial.read()
just prior to Serial.readBytes()
, it comes back with -1, meaning no bytes to read... but then Serial.readBytes()
gives me the byte stream I was expecting from the buffer! What's going on here?
Similarly, Serial.available()
seems sort of broken in that it tells me there are no bytes to read (returns 0), but then I can read the bytes I'm expecting with Serial.readBytes()
. Additionally, I can do Serial.readBytes()
after there's nothing left (or rather, there shouldn't be any bytes left...) and it will give me some bytes, but they're total garbage.
I think maybe there's something I don't understand about the way the serial buffer works, but can't find a good resource on it and the Arduino reference pages are kind of useless. Any clues about the difference in how these operate would be much appreciated!