Reputation: 13
I am developing a MATLAB GUI which is supposed to get serial data and plot it after processing. I use
bytesavailabefcn
a callback function which is executed when a pre-specified number of bytes (bytesavailablefcncount
) become available.
The code works well and gets the serial data. But when using plotyy
to plot the data it opens a new figure and plots the data on it rather than plotting it in the axes which is drawn in the GUI and is tagged as axes1
. I use axes(handles.axes1)
to assign it to axes1
, but the problem still exists. I am using MATLAB 2007b and can not switch to newer versions.
here is a shortened version of my code:
function pushbutton1_Callback(hObject, eventdata, handles)
...
...
global s;
s = serial('COM4'); % Create a serial object
s.baudrate = 9600;
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 21;
s.BytesAvailableFcn = {@instrcallback,gcf};
fopen(s);
...
...
end
function instrcallback(hObject, eventdata,fignum)
...
...
handles = guidata(fignum);
global s;
axes(handles.axes1);
[ax,h1,h2] = plotyy(G1,m1,G1,m2);
set(ax(1),'YLim',[(y1offset -zoom1-10), (y1offset +zoom1+10)]);
set(ax(2),'YLim',[(y2offset -zoom2-10), (y2offset +zoom2+10)]);
set(ax(1),'BOX' ,'off');
set(ax(1),'Xgrid','on');
set(ax(2),'Ygrid','on');
drawnow;
...
...
end
Upvotes: 1
Views: 553
Reputation: 32084
The correct syntax is: [ax,h1,h2] = plotyy(handles.axes1, G1,m1,G1,m2);
Recommended updates:
In pushbutton1_Callback
:
Replace {@instrcallback,gcf};
with {@instrcallback, handles};
:
function pushbutton1_Callback(hObject, eventdata, handles)
...
s.BytesAvailableFcn = {@instrcallback, handles};
In instrcallback:
use the following syntax:
function instrcallback(hObject, eventdata, handles)
[ax,h1,h2] = plotyy(handles.axes1, G1,m1,G1,m2);
...
According to documentation:
axes(cax) makes the axes or chart specified by cax the current axes and brings the parent figure into focus.
I can't figure out why a new figure is opened.
Here is a code that reproduce the problem using a Timer
instead of serial
:
function pushbutton1_Callback(hObject, eventdata, handles)
t = timer;
handles.t = t;
guidata(hObject, handles)
t.TimerFcn = {@instrcallback,handles};
t.ExecutionMode = 'fixedRate';
t.StartDelay = 1;
t.Period = 1;
start(t)
function instrcallback(hObject, eventdata, handles)
axes(handles.axes1);
plot(sin(-3:0.1:3 + rand(1)));
The problem repeats using MATLAB R2019a in Windows 10.
Upvotes: 1