diff --git a/java/libraries/serial/src/processing/serial/Serial.java b/java/libraries/serial/src/processing/serial/Serial.java index b57dc242a..4b1474d8f 100644 --- a/java/libraries/serial/src/processing/serial/Serial.java +++ b/java/libraries/serial/src/processing/serial/Serial.java @@ -341,6 +341,37 @@ public class Serial implements SerialPortEventListener { } + /** + *

Advanced

+ * Return a byte array of anything that's in the serial buffer + * up to the specified maximum number of bytes. + * Not particularly memory/speed efficient, because it creates + * a byte array on each read, but it's easier to use than + * readBytes(byte b[]) (see below). + * + * @param max the maximum number of bytes to read + */ + public byte[] readBytes(int max) { + if (inBuffer == readOffset) { + return null; + } + + synchronized (buffer) { + int length = inBuffer - readOffset; + if (length > max) length = max; + byte[] ret = new byte[length]; + System.arraycopy(buffer, readOffset, ret, 0, length); + + readOffset += length; + if (inBuffer == readOffset) { + inBuffer = 0; + readOffset = 0; + } + return ret; + } + } + + /** *

Advanced

* Grab whatever is in the serial buffer, and stuff it into a