如何在 MATLAB 中格式化从串行端口读取的数据?
我正在尝试通过 MATLAB 将数字传感器连接到我的计算机。
我首先向传感器发送数据请求,然后传感器用六字节流进行回复。
MATLAB 像这样读取传感器:
data1 = fscanf(obj1, '%c', 6);
我确切地知道数据的内容应该是什么,但我不知道如何读取 MATLAB 生成的数据包中的数据。
数据包 (data1
) 只有 6 个字节,但如何以整数形式访问每个单独的元素?
我以前从未接触过 MATLAB 编程,所以我有点迷失。
附带问题:MATLAB 的数据格式 %c
、%s
、%c\n
和 有何作用>%s\n
是什么意思?我试着寻找它,但我什么也没找到。
I'm trying to interface a digital sensor to my computer via MATLAB.
I first send a request for data to the sensor, then the sensor replies with a six byte stream.
MATLAB reads the sensor like this:
data1 = fscanf(obj1, '%c', 6);
I know exactly what the contents of the data is supposed to be, but I don't know how to read the data in the packet that MATLAB produced.
The packet (data1
) is simply 6 bytes, but how do I access each individual element as an integer?
I've never touched MATLAB programming before so I'm kind of lost.
Side question: What do MATLAB's data formats %c
, %s
, %c\n
, and %s\n
mean? I tried searching for it, but I couldn't find anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
格式说明符
%c
表示 FCANF 正在读取六个字符。您应该能够使用 DOUBLE 将这些字符转换为整数值 函数:现在
data1
应该是一个包含整数值的六元素数组。您可以通过索引到数组来访问每个内容:如果您想要组合
data1
中的一对值,使一个值代表数字的最高 8 位,一个值代表最低 8 位,则以下内容应该可行:上面使用
data1(1 )
作为高位,data1(2)
作为低位,然后将结果转换为 INT16 类型。您还可以停止对 INT16 的调用,而将结果保留为 DOUBLE 类型(它存储的值仍然是整数)。格式说明符
%s
用于读取字符串,直到遇到空格为止。我在上面链接到的 FCANF 文档中讨论了格式说明符。The format specifier
%c
indicates that FSCANF is reading six characters. You should be able to convert those characters to integer values using the DOUBLE function:Now
data1
should be a six-element array containing integer values. You can access each by indexing into the array:If you want to combine pairs of values in
data1
such that one value represents the highest 8 bits of a number and one value represents the lowest 8 bits, the following should work:The above uses
data1(1)
as the high bits anddata1(2)
as the low bits, then converts the result to an INT16 type. You could also leave off the call to INT16 to just leave the result as type DOUBLE (the value it stores would still be an integer).The format specifier
%s
is used to read a string of characters, up until white space is encountered. Format specifiers are discussed in the documentation for FSCANF that I linked to above.您可以使用 MATLAB File Exchange 中 AJ Johnson 的 cstruct。这允许您指定与字符包相对应的 C 语言数据结构。然后,一个函数调用将字符(字节)转换为 MATLAB 数据类型。如果数据格式发生变化,这是快速且相当可维护的。
You can use cstruct by AJ Johnson from MATLAB File Exchange. This allows you to specify a C-language data structure that corresponds to your packet of characters. Then one function call translates the characters (bytes) into MATLAB data types. This is fast and quite maintainable if the data format ever changes.