Hi Brendan,
To automatically and continuously update the IR sensor reading (without pressing the button each time), a ‘timer’ object is better suited than ‘timefcn’ for GUI-based applications in MATLAB. Refer to the documentation of ‘timer’ class to know about related arguments and their syntax. https://www.mathworks.com/help//releases/R2021a/matlab/ref/timer-class.html
Here is a sample code of how we can achieve that:
Modify the ‘ir_sensor1_OpeningFcn’ function to add ‘timer’ object initialization as follows:
function ir_sensor1_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for ir_sensor1
handles.output = hObject;
% Initialize Arduino
global a;
a = arduino('COM5'); % Update port if needed
% Set up timer for automatic reading
handles.t = timer('ExecutionMode', 'fixedSpacing', ...
'Period', 1, ...
'TimerFcn', {@updateSensor, hObject});
start(handles.t); % Start timer
% Update handles structure
guidata(hObject, handles);
‘pushbutton1_Callback’ function needs to be replaced by ‘updateSensor’ function. Here is the sample code for the same:
function updateSensor(~, ~, hObject)
handles = guidata(hObject);
global a;
% Read sensor
voltage = 100 * readVoltage(a, 'A0');
% Update GUI text
if isfield(handles, 'valtxt') && ishandle(handles.valtxt)
set(handles.valtxt, 'String', voltage);
end
if isfield(handles, 'racetext') && ishandle(handles.racetext)
if voltage <= 90
%If condition
else
%Else condition
end
end
end

