Reading raw serial data in Matlab

北城余情 提交于 2020-01-17 02:21:26

问题


I'm trying to read some raw telemetry data via serial. Each message terminates with \r\n and there are 4 kinds of messages.

I setup the port like this:

if exist('s')
    fclose(s);
    delete(s);
    clear s;
end

s = serial('/dev/ttyS99');
s.BaudRate = 57600;
s.BytesAvailableFcnMode = 'terminator';
s.Terminator = 'CR/LF';
s.DataBits = 8;
s.Parity = 'none';
s.StopBits = 1;

s.BytesAvailableFcn = @serial_callback;
s.OutputEmptyFcn = @serial_callback;

fopen(s);

For the calback, i wrote a simple function

function serial_callback(obj, event)
if (obj.BytesAvailable > 0)
    [serial_out, count] = fscanf(obj);
    disp(count)
    end

end
end

Using fscanf, I get random message lengths. For instance, I am searching for a message with length 42, and it only retrieves messages with length near that value (40, 43, 46...).

I i use fread with unspecified size, I allways get a full 512 bytes buffer. If I specify the size in fread with get(obj, 'BytesAvailable), it degenerates in the sizes of fscanf, i.e., totally random.

So, am I doing something wrong, is matlab bad for parsing serial data...?

P.S. I am getting something like 40 messages of 20~40 bytes per second.


回答1:


  1. Call the callback function everytime a \r\n has been received, using BytesAvailableFcnMode to configure. fscanf should only be called when a line is completely received by the buffer.
  2. Use fgets or fgetl to read one line from file. This will keep all things after the first \r\n in the buffer. I don't have a serial port nor a Tek so I can't verify this to be working for serial ports.
  3. Probably you need a while loop to read all lines in the buffer. Again I'm not sure how serial does callback but it's unlikely to continuously triggering callback function when there's nothing newly arrived after callback has been called.


来源:https://stackoverflow.com/questions/24940876/reading-raw-serial-data-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!