Методы реализации таймера в MATLAB Designer с примерами кода

Чтобы реализовать таймер в конструкторе MATLAB, вы можете использовать объект Timer, предоставленный классом Timer MATLAB. Объект Timer позволяет выполнять код через заданные интервалы времени. Вот несколько методов с примерами кода:

Метод 1: использование свойства TimerFcn

% Create a figure and a button in the designer
% Set the button's Callback property to 'startTimer'
% In the TimerFcn property of the timer object, add the code you want to execute at each interval
function timerCallback(~, ~)
    disp('Timer callback executed.');
end
function startTimer(~, ~)
    % Create a timer object
    t = timer;

    % Set the timer properties
    t.StartDelay = 0;
    t.Period = 1;  % Execute the timer callback every 1 second
    t.ExecutionMode = 'fixedRate';
    t.TimerFcn = @timerCallback;

    % Start the timer
    start(t);
end

Метод 2. Использование методов start и stop объекта Timer

% Create a figure and a button in the designer
% Set the button's Callback property to 'startTimer' and create a stop button with 'stopTimer' as the Callback property
function timerCallback(~, ~)
    disp('Timer callback executed.');
end
function startTimer(~, ~)
    % Create a timer object
    t = timer;

    % Set the timer properties
    t.StartDelay = 0;
    t.Period = 1;  % Execute the timer callback every 1 second
    t.TimerFcn = @timerCallback;

    % Start the timer
    start(t);
end
function stopTimer(~, ~)
    % Get the timer object
    t = timerfind;

    % Stop and delete the timer
    stop(t);
    delete(t);
end

Метод 3: использование GUIDE (среды разработки графического пользовательского интерфейса)

  1. Откройте GUIDE, набрав guideв командном окне MATLAB.
  2. Создайте новый графический интерфейс с кнопкой и компонентом осей.
  3. Дважды щелкните кнопку, чтобы открыть редактор обратного вызова.
  4. В редакторе добавьте следующий код:

    function startTimer_Callback(hObject, eventdata, handles)
    % Create a timer object
    t = timer;
    
    % Set the timer properties
    t.StartDelay = 0;
    t.Period = 1;  % Execute the timer callback every 1 second
    t.ExecutionMode = 'fixedRate';
    t.TimerFcn = @(~,~)timerCallback(handles.axes1);  % Pass the axes component to the callback function
    
    % Start the timer
    start(t);
    
    % Store the timer object in the GUI's data
    handles.timer = t;
    guidata(hObject, handles);
    end
    function timerCallback(axesObj)
    % Execute code to update the axes or perform other tasks
    % For example, to update the plot in the axes component:
    plot(axesObj, rand(1, 10));
    end
    function stopTimer_Callback(hObject, eventdata, handles)
    % Get the timer object
    t = handles.timer;
    
    % Stop and delete the timer
    stop(t);
    delete(t);
    
    % Remove the timer object from the GUI's data
    handles.timer = [];
    guidata(hObject, handles);
    end