MATLAB: How to avoid calling Arduino all the times in a timer function

arduinodefine arduino objectguitimer

Hi, I made a GUI where I put a timer with the timer function linked to Arduino. So to get data from Arduino I need to define his port and type everytime and this wastes a huge amount of time. How can I avoid defining the arduino properties all the time?
I tried to put a global a, arduino object, but it doesn't seem to work.
This is the GUI Function callback:
function CmdStart_Callback(hObject, eventdata, handles)
global txtTime Timer1
set(handles.CmdStart, 'Enable', 'Off'); %Disabilita il bottone per lo start dopo che questo รจ stato premuto.
disp('Start Timer');
Timer1= timer('name','Period');
Timer1.ExecutionMode = 'FixedSpacing';
Timer1.Period = txtTime;
Timer1.TimerFcn = @SoilHumidityforGUI;
Timer1.ErrorFcn = @ErrorFcn;
start (Timer1);
end
And this is the function called by the timer.
function SoilHumidityforGUI (~,~)
a= arduino ('com3', 'mega2560');
H= (readVoltage (a, 'A0'));
end
Thanks

Best Answer

Elena - store the Arduino object in the handles structure so that you don't have to re-initialize each time. I would do this for the timer objet too so that you have the means to stop the timer from (say) a stop callback button.
For example,
function CmdStart_Callback(hObject, eventdata, handles)
set(handles.CmdStart, 'Enable', 'Off');
disp('Start Timer');
handles.Timer1= timer('name','Period');
handles.Timer1.ExecutionMode = 'FixedSpacing';
handles.Timer1.Period = txtTime;
handles.Timer1.TimerFcn = {@SoilHumidityforGUI, hObject};
handles.Timer1.ErrorFcn = @ErrorFcn;
handles.arduinoObj = arduino ('com3', 'mega2560');
% save the updated handles object
guidata(hObject, handles);
start(handles.Timer1);
When we call guidata, the handles structure is updated with the timer and Arduino objects. (Note how I've removed the global declaration. This is no longer needed for Timer1 but still may be for your txtTime although you may be able to use handles for this too.)
Also, see how the timer callback has been declared
handles.Timer1.TimerFcn = {@SoilHumidityforGUI, hObject};
We are passing another parameter to this function (besides the default ones) which is the handle to pushbutton. The idea is that we will use this to retrieve the handles structure from within the timer as
function SoilHumidityforGUI (~,~,hObject)
handles = guidata(hObject);
if isfield(handles,'arduinoObj')
H= (readVoltage (handles.arduinoObj, 'A0'));
else
fprintf('Error - cannot find arduinoObj in handles structure!!\n');
end
I haven't tested the above, so try it out and see what happens!
Related Question