我正在开展一个项目,通过XBees将数据从一台笔记本电脑传输到另一台笔记本电脑。我已经完成了GUI界面,但我的接收部分有问题。由于接收器不知道文件将被接收的确切时间,我写了一个无限循环:
recv=[];
while (1)
while s.BytesAvailable==0
end
a=fscanf(s);
recv=[recv a]
end
如何一直运行此for
循环,从程序的最开始直到用户关闭程序,用户仍然可以选择不同的数据进行传输?
换句话说;将任务分为两部分接收部分始终运行;发送部分仅在用户想要传输数据时起作用...
答案 0 :(得分:2)
Matlab支持异步读取操作,在端口接收数据时触发。触发器可以是最小字节数,也可以是特殊字符。
您必须使用BytesAvailableFcn
回调属性。
您可以使用setappdata
和getappdata
来存储太大的数组,以适应端口的输入缓冲区。
假设您将主图的句柄保存到名为hfig
:
主要的gui代码:
s.BytesAvailableFcnCount = 1 ; %// number of byte to receive before the callback is triggered
s.BytesAvailableFcnMode = 'byte' ;
s.BytesAvailableFcn = {@myCustomReceiveFunction,hfig} ; %// function to execute when the 'ByteAvailable' event is triggered.
recv = [] ; %// initialize the variable
setappdata( hfig , 'LargeReceivedPacket' , recv ) %// store it into APPDATA
并作为一个单独的功能:
function myCustomReceiveFunction(hobj,evt,hfig)
%// retrieve the variable in case you want to keep history data
%// (otherwise just initialize that to recv = [])
recv = getappdata( hfig , 'LargeReceivedPacket' )
%// now read all the input buffer until empty
while hobj.BytesAvailable>0
a=fscanf(hobj);
recv=[recv a]
end
%// now do what you want with your received data
%// this function will execute and return control to the main gui
%// when terminated (when the input buffer is all read).
%// it will be executed again each time the 'ByteAvailable' event is fired.
%//
%// if you did something with "recv" and want to save it, use setappdata again:
setappdata( hfig , 'LargeReceivedPacket' , recv ) %// store it into APPDATA
答案 1 :(得分:0)
我不熟悉MATLAB,但在大多数编程环境中,您将对串行端口上的输入进行无限循环检查,然后处理来自GUI的任何事件。如果您更改内部while
循环,则可以在while(1)
:
recv=[];
while (1)
while s.BytesAvailable>0
a=fscanf(s);
recv=[recv a]
end
; Check for GUI events
end