【问题标题】:Reading between serial ports using the Bytes Available function in Matlab使用 Matlab 中的 Bytes Available 函数在串行端口之间读取
【发布时间】:2013-07-10 09:24:54
【问题描述】:

我正在尝试在 Matlab 中构建一个串口设备。我有 2 个设备“COM1”和“COM2”。 'COM1' ASYNCHROUNOUSLY 将数据写入串行端口 'COM2'。我有 'COM1' 和 'COM2' 的替代名称,如下所示:

global serialcom
serialcom=serial('COM1'); %Serial Communication portal COM 1
global testdummy
testdummy=serial('COM2'); %Serial Communication portal COM 2

testdummy 的输入缓冲区中触发 testdummy 函数的字节数为 2,这是使用 testdummy.BytesAvailableFcnCount 字段指定的 (belo)。

testdummy.BytesAvailableFcnMode = 'Byte';
testdummy.BytesAvailableFcnCount = 2;
testdummy.BytesAvailableFcn = @testdummycomfunction;

我在testdummy端有一个函数"testdummyfunction",它是使用Matlab中的BytesAvailable回调属性触发的。这个函数的结构如下:

function testdummyfunction(testdummy,BytesAvailable)
% TESTDUMMYFUNCTION(testdummy,...BytesAvailable)
% INPUTS:
% TESTDUMMY:refers to the serial port testdummy
% BYTESAVAILABLE:Refers to the callback function 'BytesAvailablefunction'

    global serialcom;
    data_string=fscanf(serialcom); %Reads the data sent form serialcom

end

现在,假设我将一个长度大于 2 个字节(比如 10 个字节)的字符串从串行通信端异步打印到 testdummy 端。虽然我知道当 testdummy 的输入缓冲区中有 2 个字节时会触发 testdummyfunction,但 data_string 是否也总是包含一个 2 个字节长的字符串? 如果不是,如何确保它只读取 2 个字节的数据?

【问题讨论】:

    标签: matlab file-io serial-port communication serial-communication


    【解决方案1】:

    您可以为 fscanf 添加一个额外的大小参数:

    fscanf(serialcom,'%c',2);
    

    使用doc serial.fscanf 获取函数的完整可选参数集。

    【讨论】:

    • 谢谢!正是我需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多