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!