Not able to read into Matlab from serial (Arduino) using a timer.

2 views (last 30 days)
I have a stopwatch code running in Arduino. I want to make a GUI in Matlab that shows the time and also has buttons to control the stopwatch.
I am using a timer in Arduino to increment the second of the stopwatch. When this happens, I want to send a serial command to Matlab so I can update the GUI.
I made a timer function that gets called 4 times a second. Its getting called, but I cannot read anything from serial inside. This is my first experience with serial communication and I'm a complete beginner with Matlab so I hope someone can help me out.
I have the following code inside the OpeningFcn function:
global s;
s = serial('COM11','BaudRate', 115200);
set(s,'Terminator','LF');
set(s,'Timeout',0.2);
fopen(s);
%s.ReadAsyncMode = 'manual';
pause(3);
disp('Connected.');
handles.timer = timer('Period',0.25, ...
'StartDelay',1, ...
'TasksToExecute',inf, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@timerCallback});
start(handles.timer);
And I have this for the timer function:
function timerCallback(~,~)
try
readasync(s);
n = s.BytesAvailable;
if n > 0
in = fscanf(s);
disp(in);
end
catch
end
end
In Arduino I'm using Serial.println(second);
Before I was using a while loop instead of a timer (in Matlab) and I could read the data. But the GUI never showed up since the code was stuck inside the loop.

Answers (1)

Geoff Hayes
Geoff Hayes on 21 Mar 2015
Ahmed - how does the timerCallback know about s since it isn't declared there as a global or otherwise? Rather than making is a global variable, you could add s to your handles structure and then access that from your callback. In the OpeningFcn you would change the code to
% same as before
handles.s = s;
handles.timer = timer('Period',0.25, ...
'StartDelay',1, ...
'TasksToExecute',inf, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',{@timerCallback,hObject});
guidata(hObject,handles);
start(handles.timer);
Note how we pass hObject as an input parameter to timerCallback. Here we assume that hObject is the handle to your figure/GUI.
Now in the timer callback we do
function timerCallback(~,~,hObject)
handles = guidata(hObject);
if isfield(handles,'s')
try
readasync(handles.s);
n = handles.s.BytesAvailable;
if n > 0
in = fscanf(handles.s);
disp(in);
end
catch
end
end
Try the above - perhaps it will allow you to proceed.

Categories

Find more on Instrument Control Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!