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');
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!
Best Answer