Timer function in OOP object constructor not working as expected
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I have some oop code that talks to an instrument over a serial port. I want to continually monitor for and handle messages from the instrument. I had intended to do this by setting up a timer in the constructor that calls a read/handle buffer function, but I found that timer objects defined in the constructor do not behave the way I normally expect.
The code below*1 (not full .m file) successfylly prints tick at the desired interval, but if I replace 'disp(''tick'')' with @demofunc, I get the following error*2.
Why does this happen, and how can I define a timer callback effectively through/within an object constructor? Thanks, Sean
*1
classdef zbrlinact2
properties
comobj=[];
expected_responses=[];
readmesgtimer=[];
end
methods
%(zbrlinact) function call
%This function is used to create the object and initialize the comm
%port for communication with the linear actuators.
function obj = zbrlinact2()
obj.comobj = serial('COM1','BaudRate',9600,'DataBits',8,'Parity', 'none', 'StopBits', 1);
fopen(obj.comobj);
obj.readmesgtimer = timer( 'BusyMode', 'queue', ...
'ExecutionMode', 'fixedSpacing', ...
'TimerFcn', 'disp(''tick'')', ...
'ErrorFcn', 'disp(''error'')', ...
'Period', 0.1);
start(obj.readmesgtimer);
function demofunc()
disp('read');
end
end
*2
Error while evaluating TimerFcn for timer 'timer-2'
Too many input arguments.
error
0 个评论
采纳的回答
Sean de Wolski
2012-2-2
The timer passes two input arguments to its timerfcn. The function you are using must be able to accept these.
function demo_func(obj,evt);
disp('read')
end
You could also just denyt he inputs:
function demo_func(~,~);
disp('read')
end
0 个评论
更多回答(1 个)
Walter Roberson
2012-2-2
A time callback specified as a function handle will still be called in standard callback style, with two arguments automatically added at the beginning. If your demofunction routine does not expect at least two arguments you would get the error you note.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!