matlab - 将 ASCII 串行数据分离成单独的矩阵

标签 matlab serial-port ascii scanf

这里是第一次海报。我正在使用加速度计来测量三个轴 x、y 和 z。我通过 pic 微 Controller 流式传输这三个变量,并通过 UART 以 ASCII 格式发送到我的笔记本电脑中。使用 fscanf 命令我收到一串逗号分隔的数据,格式为 x=0000,y=0508,z=0000,x=0000,y=0503,z=0000 等...我想分隔信息并放置分成以下形式的三个矩阵 x = [005, 010, 000....]; y = [503, 000, 450....]; z = [000, 000, 500.....]; 用于进一步分析、绘图等。 这是到目前为止我的代码:

clear all;
close all;

s = serial('COM4'); %assigns the object s to serial port

set(s, 'InputBufferSize', 256); %number of bytes in inout buffer
set(s, 'FlowControl', 'hardware');
set(s, 'BaudRate', 9600);
set(s, 'Parity', 'none');
set(s, 'DataBits', 8);
set(s, 'StopBit', 1);
set(s, 'Timeout',10);

disp(get(s,'Name'));
prop(1)=(get(s,'BaudRate'));
prop(2)=(get(s,'DataBits'));
prop(3)=(get(s, 'StopBit'));
prop(4)=(get(s, 'InputBufferSize'));

fopen(s); %opens the serial port
fscanf(s)

任何帮助将不胜感激,提前致谢。

最佳答案

您可以使用正则表达式:

>> str = 'x=0000,y=0508,z=0000,x=0000,y=0503,z=0000';
>> pat = '([xyz])=([0-9\.]*),?';
>> toks = regexp(str, pat, 'tokens')
toks = 

Columns 1 through 5

{1x2 cell}    {1x2 cell}    {1x2 cell}    {1x2 cell}    {1x2 cell}

Column 6

{1x2 cell}

>> toks{1}

ans = 

'x'    '0000'

pat 末尾的问号使其对没有尾随 ',' 的情况不敏感,并且如果您不希望也提取变量名称(即,在您的情况下,您可能不需要此信息,因为您知道它们总是以相同的顺序出现),然后只需删除 周围的 () [xyz]

要提取 double 形式的值,您可以执行以下操作:

newXYZ = zeros(length(toks) / 3, 1); 
newFilledLocs = zeros(size(newXYZ)); 
curRow = 1;
for nTok = 1:length(toks)
    col = [];
    switch toks{nTok}{1}
        case 'x', col = 1; 
        case 'y', col = 2; 
        case 'z', col = 3; 
        otherwise, error('Invalid variable name ''%s''', toks{nTok{1}});
    end; 
    newXYZ(curRow, col) = str2double(toks{nTok}{2});
    if all(newFilledLocs(curRow, :))
        curRow = curRow + 1; 
    end
end

关于matlab - 将 ASCII 串行数据分离成单独的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15793600/

相关文章:

python - 如何将非 ASCII 字符编码的文件重命名为 ASCII

image - 消除图像中字符的噪声

c++ - Arduino Nano:使用串行输入时,通过计时器进行的A4988步进控制不稳定

matlab - 选择排名在第一个四分位数内的值并将其标记为逻辑 '1'

为两个 SC2681 DUART 配置内核驱动程序

c - Arduino 代码中未读取字节

python - 通过可扩展嵌套 'for' 循环进行迭代,无需 itertools

java - 用于编码 ASCII 的不可映射字符,但我的文件是 UTF-8

MATLAB 在 Linux 上内存不足,尽管经常出现 "clear all"

matlab - matlab 中的 "Subliminal"消息