In asynchronous callback function, I can start and stop a timer class, but cannot wait the timer class

1 view (last 30 days)
I create a serial object and timer class object. The serial object has an asynchronous callback function( test in the following example). The timer class is the sweep, it will execute the TimerFcn every 1sec and be executed 10 times. The serial port is connected to a device. The serial port would generate the"RUN" and "STOP" response. Aft receiving the 'RUN' response, start(timer_obj). When receiving the 'STOP' response, I want to wait the timer class until it finishes, that is also the purpose of the wait function. But the whole program freeze, and the timer class go to the errofcn. If I change the Busymode from error to drop or queue. The timer class will continue to be executed if I press Ctrl+C in the command window.
Though I cannot wait the timer class, I can start/stop the timer class in the asynchronous callback function.
clear all
delete(instrfind)
sweep = timer; % create a timer class object
sweep.Period = 1;
sweep.ExecutionMode = 'fixedRate';
sweep.BusyMode = 'error';
sweep.TasksToExecute = 10;
sweep.TimerFcn = @(~,~) disp('1 seconds have elapsed');
sweep.ErrorFcn = @(~,~) disp('error appears');
slider_obj=serial('com4','timeout',5); % create a serial objet
fopen(slider_obj);
slider_obj.BytesAvailableFcn = {@test,sweep};
% test is the asynchronous callback
% function, sweep is passed to the callback function
fprintf(slider_obj,'@START1#P1000.1,'); % let the slider run, the serial port will receive two
% signals 'RUN' and 'STOP'
Below is the callback function.
function test(obj,~,timer_obj)
out = strtrim(fscanf(obj)); % read the response from the device
switch out
case 'RUN'
start(timer_obj);
case 'END'
%stop(timer_obj);
wait(timer_obj) % the timer class will stop if reach the TasksToExecute
delete(timer_obj)
end

Answers (0)

Categories

Find more on 迁移使用 GUIDE 创建的 App in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!