0
votes

I'm trying to get a data Stream from an Arduino like platform over to Matlab. I want matlab to read 15 Byte data packets, parse them and then read the next chunk.

Currently I have the problem, that matlab does not stop reading until the buffer is full.

My setup on the Matlab Side:

s=serial('COM25','BaudRate',115200, 'Terminator', 'LF')
fopen(s)
data=fscanf(s)

On the hardware side:

    usbMsg[0] =  0xA0;
    usbMsg[1] = _packetCounter;
    // ch1
    usbMsg[2] = in[3];
    usbMsg[3] = in[4];
    usbMsg[4] = in[5];
    // ch2
    usbMsg[5] = in[6];
    usbMsg[6] = in[7];
    usbMsg[7] = in[8];
    // ch3
    usbMsg[8] = in[9];
    usbMsg[9] = in[10];
    usbMsg[10] = in[11];
    // ch4
    usbMsg[11] = in[12];
    usbMsg[12] = in[13];
    usbMsg[13] = in[14];

    usbMsg[14] = '\n'; // LF

    SerialUSB.write(usbMsg, 15);

"usbMsg" and "in" are byte arrays.

Instead of just returning one message, the fscanf() command continues reading. Apparently it does not recognize the terminator.

I've tried different Terminators: 'LF/CR' 'CR' 'LF' and their ASCII equivalent Without any success.

Can anyone see where the problem is?

Thanks in advance!

EDIT:

I have an additional follow up question regarding buffers. If I would decrease the buffer size of the serial port (of the serial object within matlab) to just 15 bytes and keep reading those, would this cause data loss?

I'm not sure if there is an buffer at the usb interface and just how big it is.

1
When you set the terminator it only applies to the terminator appended to your outgoing messages. fscanf() will always pull the full contents of the serial connection's incoming buffer. I would recommend parsing it locally. - Alea Kootz
As for parsing, the incoming data is probably a character array. To pass 15 bytes at a time to your parser: for i = 1:ceil(length(data)/15); if length(data) >15; toparse = data(1:15); data = data(16:end); parse(toparse); else parse(data); end; - Alea Kootz
Hey! Great, thanks a lot. Seems obvious now that you said it :-). If you repost the comment as an answer, I can mark the Question as answered. :-) - Chuchaki

1 Answers

1
votes

When you set the terminator, it only applies to the terminator appended to your outgoing messages. fscanf() will always pull the full contents of the serial connection's incoming buffer. I would recommend parsing it locally.

As for parsing, the incoming data is probably a character array. To pass 15 bytes at a time to your parser:

for i = 1:ceil(length(data)/15)
    if length(data) >15
        toparse = data(1:15); 
        data = data(16:end); 
        parse(toparse); 
    else 
        parse(data); 
end