How can I do to break this while loop with the keyboard?

11 views (last 30 days)
I am working with the Matlab data acquisition toolbox. I have this code that generates a real-time graph of the data that the DAQ system acquires. I want to make the while loop stops when the user wants it, but I don't know how to do it. How can I modify my code to allow the user to control when to stop the test by pressing a button or ussing a specific command?
clear all
clc
% Data Acquisition Toolbox Analog Input Recorder
% Create DataAcquisition Object
% Create a DataAcquisition object for the specified vendor.
d = daq("mcc");
% Add Channels
% Add channels and set channel properties, if any.
addinput(d, "Board0", "Ai0", "Voltage");
% Set DataAcquisition Rate
% Set scan rate.
d.Rate = 9;
% Create figure for the real-time plot
figure;
plotHandle = plot(NaN, NaN);
xlabel("Time (s)");
ylabel("Amplitude");
legend("Channel 1", "Interpreter", "none");
title("Pull Out test");
% Create text box for real-time values display
valueText = annotation('textbox', [0.15, 0.75, 0.2, 0.1], 'String', 'Value: N/A kg', 'FitBoxToText', 'on');
% Initialize variables
sampleCount = 0;
dataValues = [];
% Start the data acquisition
start(d);
% Main loop for real-time data acquisition and plotting
while ishandle(plotHandle)
% Read Data
data = read(d, seconds(0.5)); % Read data for 0.5 second
% Update plot
if ~isempty(data.Time)
% Increment sample counter
sampleCount = sampleCount + length(data.Time);
% Update data values
dataValues = [dataValues, data.Variables'];
% Generate time values based on sample count and rate
timeValues = (1:sampleCount) / d.Rate;
set(plotHandle, "XData", timeValues, "YData", dataValues);
xlim([timeValues(1), timeValues(end)]);
drawnow;
% Update real-time values display
if ~isempty(dataValues)
current_value = dataValues(end);
set(valueText, 'String', sprintf('Value: %.5f kg', current_value));
end
end
% Pause for half a second before the next iteration
pause(0.1);
end

Accepted Answer

Bruno Luong
Bruno Luong on 9 Aug 2023
Try this
test
function test
fig = uifigure();
ax = uiaxes('Parent', fig);
h = plot(ax, NaN);
stop = false;
function setstop(varargin)
stop = true;
end
b = uibutton(fig, 'text', 'stop', 'ButtonPushedFcn', @setstop);
for i = 1:Inf
set(h,'YData', sin(linspace(0,2*pi)-i/10));
pause(0.03);
if stop
break
end
end
end

More Answers (0)

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!