问题
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:
- 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. - 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. - Probably you need a
while
loop to read all lines in the buffer. Again I'm not sure howserial
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