matlab串口接收数据大小达不到STMUART发送数据大小
13 views (last 30 days)
Show older comments
我是用matlab接收来自STM32串口的数据,数据的发送速度是500Hz,在串口助手上验证过没有问题,但是如果使用matlab接收就会缺少大概6s的数据,这是我的读取函数function readSensorData(app, src, ~)
% 读取数据并将数据放入队列
while src.NumBytesAvailable >= 5
% currentTime = datetime('now'); % 串口数据到达时记录时间戳
tic
frameHeader = read(src, 2, "uint8");
toc
if frameHeader(1) == 0x55 && frameHeader(2) == 0xAA
fun_data = read(src, 2, "uint8");
len = fun_data(2);
if src.NumBytesAvailable >= len + 1
if len ~= 0
dataToSend = read(src, len, "uint8");
checksum = read(src, 1, "uint8");
% 计算校验
expectedChecksum = bitcmp(mod(sum([fun_data, dataToSend]), 256), 'uint8');
if (checksum == expectedChecksum)
app.processData(dataToSend)
end
end
end
else
read(src, 1, 'uint8');
end
end
end
其中app.processData执行内容已经被我关闭,可以忽略
0 Comments
Answers (1)
cui,xingxing
on 30 Sep 2024
有可能是MATLAB 的串口数据接收处理速度不够快,导致数据丢失,特别是在 MATLAB 的串口读取性能与 STM32 数据发送速率的匹配上,不妨尝试下面的代码:
function readSensorData(app, src, ~)
% 尽量减少read的调用次数,优化接收效率
while src.NumBytesAvailable >= 5
% 一次性读取较多的数据
availableBytes = src.NumBytesAvailable;
dataBuffer = read(src, availableBytes, "uint8");
% 处理数据
idx = 1;
while idx <= length(dataBuffer) - 5 % 确保有足够的字节用于解析
if dataBuffer(idx) == 0x55 && dataBuffer(idx+1) == 0xAA
fun_data = dataBuffer(idx+2:idx+3);
len = fun_data(2);
if idx + 4 + len <= length(dataBuffer)
dataToSend = dataBuffer(idx+4:idx+3+len);
checksum = dataBuffer(idx+4+len);
% 校验
expectedChecksum = bitcmp(mod(sum([fun_data, dataToSend]), 256), 'uint8');
if checksum == expectedChecksum
app.processData(dataToSend);
end
idx = idx + 4 + len + 1; % 更新索引,跳过已处理的帧
else
break; % 数据不足,等待下次处理
end
else
idx = idx + 1; % 如果帧头不匹配,跳过字节
end
end
end
end
2 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!