storing incoming bytes in byte array not working

edited October 2015 in Library Questions

Hi,

I am trying to store a stream of incoming bytes received via serial port in a byte array and I must be doing something wrong as instead of the array being created with 12 entries the incoming bytes just overwrites the first one. Any help would greatly appreciated as I am a noob and have not been able to find a solution after hours of browsing.

Here is the code for the serial event:

void serialEvent(Serial p)
{
  byte[] inBuffer = new byte[11];

  while (p.available() > 0) {

    inBuffer = p.readBytes();
    p.readBytes(inBuffer);
    if (inBuffer != null) {
      println(inBuffer);
    }
  }
}

and this is the print:

[0] 85
[0] -86
[0] 1
[0] 0
[0] 0
[0] 0
[0] 0
[0] 0
[0] 48
[0] 0
[0] 48
[0] 1

As you can see the entries are all 0 and not 0, 1, 2 etc.

Thanks!

Answers

  • Answer ✓
        inBuffer = p.readBytes();
        p.readBytes(inBuffer);
    

    These are two different ways tow use readBytes(). I know the example in the reference has these lines too, but you should only use one. (First one creates a new array, second uses the passed array ).

    But the actual problem here is that whenever a byte is received, you overwrite your byte-array with a new one that has only one value. You should wait until the number of available bytes fits into your array maybe, i.e. like this:

    void serialEvent(Serial p)
    {
      byte[] inBuffer = new byte[11];
    
      while (p.available () >= inBuffer.length) {
        p.readBytes(inBuffer);
        if (inBuffer != null) {
          println(inBuffer);
        }
      }
    }
    
  • Thanks a lot! This worked perfectly.

Sign In or Register to comment.