Timer Callback Input Not Updated When Changed
2 views (last 30 days)
I have a timer callback function to output text at certain time intervals:
where message contains some numbers. The timer outputs the initial message correctly but when the variable message changes further down the code, the timer keeps printing the initial value of the variable message. Is there a way to tell Matlab to get the latest value of message each time the callback runs?
Steven Lord on 4 Sep 2023
The timer outputs the initial message correctly but when the variable message changes further down the code, the timer keeps printing the initial value of the variable message.
That is the expected behavior. When you define the anonymous function it "remembers" the values of the variables that appear in the anonymous function that are not input arguments to the anonymous function. Changing those values in the workspace after the anonymous function is created will not affect the "remembered" values. See the "Variables in the Expression" section on this documentation page for more information.
If you're using this in the context of a GUI, where the message is a property of the GUI, don't have the anonymous function "remember" the message itself. Have it remember the handle to the GUI object and retrieve the message property from the GUI.
If you're not using this in the context of a GUI, you could store the data in the UserData property of the timer object itself. Then your TimerFcn would need to access the UserData property of the timer object (which is passed into the TimerFcn as the first input argument) and retrieve the message from there.
For whatever reason this code doesn't display in MATLAB Answers, but if you run it in desktop MATLAB you should see it display a different message every time after the second. The first run executes when I call start and the second just before the first pause ends, before the last line of code in the loop increments the value of k stored in the timer's UserData property.
t = timer('TimerFcn', @(t, varargin) fprintf("The value of k is %d.\n", t.UserData.k), ...
'Period', 1, ... % Run TimerFcn every 1 second
'ExecutionMode', 'fixedrate', ... % Run it every one second (default is single shot)
'UserData', struct('k', 1)); % with the data stored in the timer starting at k = 1
for x = 1:10
t.UserData.k = t.UserData.k + x; % change the value of k stored in the timer