Hi Nex,
To manage parallel data acquisition from two hardware devices in MATLAB, a “parfor” loop runs two tasks concurrently: Task 1 maintains "Hardware A" data acquisition using an indefinite pause, while Task 2 continuously acquires data from "Hardware B" in an infinite loop until a user-triggered event.
Communication between tasks can be achieved using “parallel.pool.DataQueue” in MATLAB, allowing Task 2 to send a stop signal to break the pause in Task 1, effectively halting both tasks. Messages from within the “parfor” loop are managed through the “DataQueue”, ensuring they are displayed in a controlled manner.
Here is the sample MATLAB code to achieve the same:
% Create a DataQueue to communicate between workers
dq = parallel.pool.DataQueue;
% Function to handle stop signal
function handleStopSignal(~)
disp('Stop signal received');
% You might use a more complex logic here to stop your hardware
end
% Set up the listener to handle messages from the DataQueue
afterEach(dq, @handleStopSignal);
parfor i = 1:2
if i == 1
% Start hardware A data acquisition
fprintf('Hardware A started\n');
pause(); % This will pause indefinitely
% Close hardware A data acquisition
fprintf('Hardware A stopped\n');
else
while true
% Hardware B data acquisition
fprintf('Hardware B acquiring data\n');
% Simulate user input break
% In real scenario, replace this with a GUI button or condition
if rand() > 0.99 % Random condition to simulate stop
send(dq, true); % Send stop signal
break;
end
% Pause for a short duration to prevent excessive CPU usage
pause(0.1);
end
end
end
Please find attached the documentation of functions used for reference:
parallel.pool.DataQueue: www.mathworks.com/help/parallel-computing/parallel.pool.dataqueue.html
I hope this assists in resolving the issue.
