2

我有一个从 Arduino 板通过串行线路输入的数据流。流看起来像这样:

0x43 0x03 0x39 0x00 0x0D 0x0A

前两个字节(0x43 和 0x03)是单字节整数值。接下来的两个字节(0x39 和 0x00)是单个 16 位 little-endian 有符号整数值。最后两个字节(0x10 和 0x13)应该是一个终止序列(“\r\n”)。

我正在使用 MATLAB 读取这些数据。我创建了一个串行连接,打开它,然后读入数据。不幸的是,我在使用 0x00 作为字节值时遇到了问题,因为fscanf只是认为它是字符串的空终止符。

这是一些示例代码:

%Create and open serial connection
serialcon = serial('COM5');
fopen(serialcon);

firstChar = fscanf(serialcon, '%c', 1); %Read 0x43
secondChar = fscanf(serialcon, '%c', 1); %Read 0x03
integerByteChars = fscanf(serialcon, '%c', 2); %Read 0x39 and 0x00
fscanf(serialcon, '%c'); %Read until end-of-line

integerBytes = uint8(integerByteChars); %value should be (in hex): [ 0x39 0x00 ]
integerValue = typecast(integerBytes, 'uint16'); %value should be (in hex): 0x0039

不幸的是,发生的事情是“integerByteChars”不是我希望的 2 元素数组,而是 1 元素数组,因为fscanf它只是认为 0x00 是一个以空值结尾的字符串值。然而,这让我感到惊讶,因为我使用“%c”而不是“%s”(用于字符串)输入数据。

我需要的是一个函数,它可以将这些字节作为数据读取,即使它是零字节并且不会将其丢弃。我可以使用哪些功能来做到这一点?可以强制fscanf这样做吗?

4

1 回答 1

2

fread 将是这样做的好方法。

您可以使用以下命令读取所有 6 个字节:

 data = fread(s2,6,'uint8')

然后处理返回的向量。

 firstChar = data(1);
 secondChar = data(2);
 integerValue = data(3) + data(4) * 256;  % Need to check endian calc
 if data(5) ~= 13 || data(6) ~= 10
    error('Not terminated correctly')
 end

顺便说一句,你确定你的 CR/LF ASCII 值正确吗?

于 2012-03-14T07:34:35.707 回答