Timer function in OOP object constructor not working as expected

3 ビュー (過去 30 日間)
Sean
Sean 2012 年 2 月 2 日
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

採用された回答

Sean de Wolski
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

その他の回答 (1 件)

Walter Roberson
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by