在Matlab中读取原始串行数据 [英] Reading raw serial data in Matlab

查看:105
本文介绍了在Matlab中读取原始串行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过串行读取一些原始遥测数据.每条消息均以\r\n结尾,并且有4种消息.

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

我这样设置端口:

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

使用fscanf,我得到了随机的消息长度.例如,我正在搜索长度为42的消息,并且它仅检索长度接近该值(40、43、46 ...)的消息.

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...).

我使用未指定大小的fread,我总是获得完整的512字节缓冲区.如果我在fread中用get(obj, 'BytesAvailable)指定大小,则会退化为fscanf的大小,即完全随机.

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.

那么,我做错什么了吗,matlab对解析串行数据有害吗??

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

P.S.我收到了40条每秒20〜40字节的消息.

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

推荐答案

  1. 每次使用 进行配置.仅当缓冲区完全接收到一行时才调用fscanf.
  2. 使用 fgets
  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.

这篇关于在Matlab中读取原始串行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆