gpt4 book ai didi

multithreading - 如何连续从Matlab的串口读取?

转载 作者:行者123 更新时间:2023-12-03 13:12:23 27 4
gpt4 key购买 nike

这是我的代码:

serialPort = 'COM3';
s = serial(serialPort,'BaudRate',9600);
if (s.Status == 'closed')
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 200;
s.BytesAvailableFcn = @Serial_OnDataReceived;

fopen(s);
end

这是回调函数
function Serial_OnDataReceived(obj,event)
global s;
global i;
global endCheck;
global yVals;
global xVals;

if (s.Status == 'open')
while s.BytesAvailable > 0 && endCheck ~= '1',
data = str2num(fgetl(s));
dlmwrite ('SensorsReading.csv', data, '-append');

yVals = circshift(yVals,-1);
yVals(end) = data(3);

xVals = circshift(xVals,-1);
i = i + 0.0125;
xVals(end) = i;
end

figure(1);
plot(xVals,yVals);

end

结尾

FOPEN函数之后,我得到以下警告:

The BytesAvailableFcn is being disabled. To enable the callback property either connect to the hardware with FOPEN or set the BytesAvailableFcn property.



回调函数 Serial_OnDataReceived中发生的逻辑是否在其他线程上运行?

有没有办法将参数传递给函数?我想通过不同文件中的回调函数来修改主脚本中的数组。最好的方法是什么?
我还尝试在更新值以显示某种动态动画时绘制这些值。

最佳答案

我不知道是什么产生了警告,但是要回答您的其他问题(如何将参数传递给回调以及如何更新绘图),更好的方法是在回调之外准备您的绘图,然后将句柄传递给回调仅用于更新。

nPointsInFigure = 10 ;  %// number of "sliding points" in your figure
step = 0.0125 ; %// X points spacing
xVals = linspace(-(nPointsInFigure-1)*step,0,nPointsInFigure) ; %// prepare empty data for the plot
yVals = NaN(nPointsInFigure,1) ;

figure(1) ;
hp = plot( xVals , yVals ) ; %// Generate the plot (with empty data) it will be passed to the callback.

serialPort = 'COM3';
s = serial(serialPort,'BaudRate',9600);
if (s.Status == 'closed')
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 200;
s.BytesAvailableFcn = {@Serial_OnDataReceived,hp,step} ; %// note how the parameters are passed to the callback
fopen(s);
end

您的回调将变为:
function Serial_OnDataReceived(obj,event,hp,step)

global endCheck; %// I don't know how you use that so I could not get rid of it.

xVals = get(hp,'XData') ; %// retrieve the X values from the plot
yVals = get(hp,'YData') ; %// retrieve the Y values from the plot

while obj.BytesAvailable > 0 && endCheck ~= '1',
data = str2num(fgetl(s));
dlmwrite ('SensorsReading.csv', data, '-append');

yVals = circshift(yVals,-1);
yVals(end) = data(3);

xVals = circshift(xVals,-1);
xVals(end) = xVals(end-1) + step ;
end

set( hp , 'XData',xVals , 'YData',yVals ) ; %// update the plot with the new values

另请注意:(1)您无需在回调函数中检查串行端口的打开/关闭状态。如果事件被触发,则表示该端口已打开。 (2)您不需要将 s声明为全局变量, obj参数实际上是串行对象本身。

关于multithreading - 如何连续从Matlab的串口读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973017/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com