Skip to content

Commit 724b9ae

Browse files
committed
Added readBytes(max) to serial library
1 parent 344dcb3 commit 724b9ae

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

java/libraries/serial/src/processing/serial/Serial.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,37 @@ public byte[] readBytes() {
341341
}
342342

343343

344+
/**
345+
* <h3>Advanced</h3>
346+
* Return a byte array of anything that's in the serial buffer
347+
* up to the specified maximum number of bytes.
348+
* Not particularly memory/speed efficient, because it creates
349+
* a byte array on each read, but it's easier to use than
350+
* readBytes(byte b[]) (see below).
351+
*
352+
* @param max the maximum number of bytes to read
353+
*/
354+
public byte[] readBytes(int max) {
355+
if (inBuffer == readOffset) {
356+
return null;
357+
}
358+
359+
synchronized (buffer) {
360+
int length = inBuffer - readOffset;
361+
if (length > max) length = max;
362+
byte[] ret = new byte[length];
363+
System.arraycopy(buffer, readOffset, ret, 0, length);
364+
365+
readOffset += length;
366+
if (inBuffer == readOffset) {
367+
inBuffer = 0;
368+
readOffset = 0;
369+
}
370+
return ret;
371+
}
372+
}
373+
374+
344375
/**
345376
* <h3>Advanced</h3>
346377
* Grab whatever is in the serial buffer, and stuff it into a

0 commit comments

Comments
 (0)