MATLAB: Executing two timer functions continuously. GUI.

matlab guitimer

Dear experts,
this is Carlos Andreu. Several months ago, You helped me to refresh continously a textbox with a timer function. This solution has worked perfectly. Now, I would like to add other timer function in order to refresh two text boxes at the same time. I have tried it with the following code:
function myGUI(handles,hObject)
TimerH = timer('UserData', handles.text5, 'TimerFcn', @myTimerFcn, 'Period', 0.5, ...
'ExecutionMode', 'fixedRate');
drawnow;
TimerH2 = timer('UserData', handles.text9, 'TimerFcn', @myTimerFcn2, 'Period', 0.6, ...
'ExecutionMode', 'fixedRate');
drawnow;
start([TimerH TimerH2]);
function myTimerFcn(TimerH,eventData,handles,hObject)
global distance
global flag_tracker
if flag_tracker == 1
TextH = get(TimerH, 'UserData');
distancia = Guardar_pos(TextH);
pause(0.5)
set(TextH,'String',num2str(distance))
drawnow();
else
TextH = get(TimerH, 'UserData');
set(TextH,'String','Measuring...');
end
function myTimerFcn2(TimerH2,eventData,handles,hObject)
global distance2
global flag_tracker
if flag_tracker == 1
TextH2 = get(TimerH2, 'UserData');
distancia_fija = Guardar_pos3(TextH2);
pause(0.5)
set(TextH2,'String',num2str(distance2))
drawnow();
else
TextH2 = get(TimerH2, 'UserData');
set(TextH2,'String','Measuring...');
end
The problem is the textbox of timerH works, but textbox of timerH2 doesn't.
Please, Can you help me?
Thank you in advance,
Carlos.

Best Answer

Using global variables is a bad idea in general. If you see a way to avoid them, do this.
You did not mention, what is not working. Do you get an error message? Is the timer function entered?
Why do you calculate the values.
distancia = Guardar_pos(TextH);
and
distancia_fija = Guardar_pos3(TextH2);
when the variables are not used at all? What is "Guardar_pos" and "Guarder_pos3"?
If you define the TimerFcn as "@myTimerFcn2", it is called with 2 inputs: The handle of the timer and the EventData struct. Then requesting 4 inputs is not smart, although it is not an error, when the not provided inputs are not used in the function:
function myTimerFcn2(TimerH2,eventData,handles,hObject)
% Better:
function myTimerFcn2(TimerH2,eventData)
There is no need for a drawnow after creating a timer object. But after setting a string, drawnow is required to see the changes. A simplified timer callback:
function myTimerFcn2(TimerH2,eventData)
global distance2 flag_tracker
TextH2 = get(TimerH2, 'UserData');
if flag_tracker == 1
% distancia_fija = Guardar_pos3(TextH2); % Is this needed at all?
% pause(0.5)
set(TextH2, 'String', num2str(distance2))
else
set(TextH2, 'String', 'Measuring...');
end
drawnow;
Related Question