MATLAB: Collecting a variable every two minutes

variable collectiojn

Hi, I have a function running in the background that gives me a different value for the variable x every two minutes. Now the question is how can I collect the value in a table for every two minutes, ie. time and the value 15:02 value 43, 15:04 value 7.3 and so on.
Has anyone got an idea?

Best Answer

AA - is your timer started from within your GUI, or outside of it? If the former, then if you set up your timer in such a way that it can access the handles object of the GUI, then the timer can update the table every two minutes.
For example, suppose that your timer starts when you press a button in your GUI. The pushbutton callback looks something like
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.timer = timer('Name','MyTimer', ...
'Period',15, ...
'StartDelay',1, ...
'TasksToExecute',inf, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@timerCallback,handles.figure1});
guidata(hObject,handles);
start(handles.timer);
The above timer will fire every 15 seconds. Note how we pass the GUI figure handle as an input to the timerCallback function. This is necessary so that we can access the handles structure in the timer callback. Now, define this callback as
function [] = timerCallback(~,~,guiHandle)
if ~isempty(guiHandle)
% get the handles
handles = guihandles(guiHandle);
% format the current time
currentTime = datestr(now,'HH:MM:SS');
% collect a number
x = randi(255,1,1);
% update the table
data = get(handles.uitable1,'Data');
data = [data ; {currentTime , x}];
set(handles.uitable1,'Data',data);
end
In the above, we get the handles structure using guihandles so that we can get the current set of data in the uitable1 control. We then add a row with the current time and x value, and set this new data to the table.