MATLAB: Addpoints error “Value must be a handle”

addpointsanimatedlinearduinocallbacksdata acquisitionhandlesMATLAB

Aim: Continuously read & plot data acquired from Arduino Uno + pressure transducer setup using "animatedline". After the experiment is done, hit "STOP" button on GUI, and gather data collected using "getpoints" to then be processed as necessary.
Problem: When I run the code, I am able to plot live signal from my transducer using "animatedline" (illustrated below).
The code that enables this is the following:
figure
an = animatedline('Marker','.','Color','r','LineWidth',1.5);
ax = gca; box on
ax.XGrid = 'on'; ax.YGrid = 'on';
ax.YLim = [0 32]; % psi
ButtonHandle = uicontrol('Style', 'PushButton', ...
'String', 'STOP', ...
'BackgroundColor','r',...
'Callback', 'exit_loop');
startTime = datetime('now');
eject = 0;
while t < 10
voltage = readVoltage(a,'A0');
maxP = 30; minP = 0; % Dictated by transducer
pOffset = 7.44; % Observed voltage correction
pressure = voltage*((maxP-minP)/(5-1))-pOffset; % Convert signal to pressure
t = datetime('now') - startTime;
addpoints(an,datenum(t),pressure) % adds points to plot
ax.XLim = datenum([t-seconds(15) t]); % updates the x-axis
datetick('x','keeplimits') % change x-axis to time label
drawnow limitrate
end
The code for the "STOP" button in the bottom left corner is below. I have this saved as a separate script, but in the same folder:
function exit_loop(hObject, eventdata, handles)
selection = questdlg('Sure you want to exit?',...
'Close Request Function',...
'Yes','No','Yes');
switch selection
case 'Yes'
delete(gcf)
case 'No'
return
end
Once I hit "Yes," however, I then get this error:
Error using matlab.graphics.animation.AnimatedLine/addpoints
Value must be a handle.
Error in pRecord_v0 (line 117)
addpoints(an,datenum(t),pressure) % adds
points to plot
Same error when I try to store the data from the experiment using the following:
[timeLog,pLog] = getpoints(an);
Any help you can offer is much appreciated!

Best Answer

Guard your addpoints call with a check to make sure the animatedline handle still isvalid.
L = animatedline;
axis([0 360 -1 1]);
for d = 0:360
if isvalid(L)
addpoints(L, d, sind(d));
else
break % stop trying to add points
end
if d == 180
cla % get rid of the animatedline
end
drawnow expose
end
disp(d) % 181
Related Question