Sending specific amount of bytes of data

I am using my Arduino to send data from a sensor into MATLAB using serial communication. I want to just send a set amount of bytes of data. I know you can read in a specific amount of bytes (serial.readBytesUntil) or set the amount of characters to send but is there any way to specify sending exactly 512 bytes of data and then stopping? Any help or suggestions would be greatly appreciated :slight_smile:

Im inclined to suggest a byte array that has 512 elements. Or an int array that has 256 elements or even a long array of 128 elements.

For any of the combinations above, use a union.

Could I use Serial.write(buf, len)? Would that work the same as serial.print? Then I would just have to create a byte array and specify it's length. To create a byte array would you just create an array while reading in the data and specify it is bytes rather than characters?

Like this, yes.

byte array[4] = {10, 244, 3, 42};

void setup()
{
  Serial.begin(115200);
  Serial.write(array, 4);
}

void loop()
{
  
}

I would do exactly the same as @HazardsMind has suggested in Reply #3

However ...
You may want to consder if it would be more convenient for the receiving program to send the data as (for example) Comma Separated Values (CSV) like 10,244,3,42 in which case there would not be a fixed number of bytes.

Adding start and end markers is a good idea for improved reliability whether you are sending CSV data of otherwise - for example <10,244,3,42>

...R