Turning on and off leds with Arduino with parallel loops

8 views (last 30 days)
Hi everyone,
I am trying to turn on and off leds randomly but independently. I think it might be doable with parallel loops, but I get an error saying "Arduino objects cannot be saved to disk, and will be skipped." Is it possible to do what I am trying?
a = arduino();
t1 = parfevalOnAll(backgroundPool, @f1, 1, a, 'D7')
t2 = parfevalOnAll(backgroundPool, @f1, 1, a, 'D4')
v1 = fetchOutputs(t1);
v2 = fetchOutputs(t2);
clear
function [tx, ty] = f1(a, pin)
tx = zeros(10, 1);
ty = zeros(10, 1);
for i = 1:10
writeDigitalPin(a, pin, 1);
x = rand(1);
tx(i) = x;
pause(x)
writeDigitalPin(a, pin, 0);
y = 2 * rand(1);
ty(i) = y;
pause(y)
end
end

Answers (2)

Taylor
Taylor on 25 Sep 2024
The issue you're encountering is related to the fact that arduino objects are not serializable and cannot be passed directly to parallel workers because they cannot be saved to disk. When using parallel processing in MATLAB, each worker operates in its own separate process, and objects like arduino cannot be directly shared across these processes.
If your goal is to toggle each LED randomly and independently you could try just creating the random order of pins and delay times before entering the loop, and then just loop through them. In the code below, you would just replace the display commands with your function to toggle the specified pin on/off.
pins = "D" + (1:10)
pins = 1x10 string array
"D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10"
randIdx = randperm(length(pins));
pauseTimes = rand([1 10]);
for ii = randIdx
disp(pins(ii))
disp(pauseTimes(ii))
end
D7
0.6864
D8
0.2819
D3
0.5752
D4
0.8155
D1
0.6598
D5
0.4251
D2
0.9067
D10
0.1653
D9
0.4702
D6
0.8848

MathWorks MATLAB Hardware Team
Hi,
MATLAB Support Package for Arduino Hardware doesn't support parallel executions. Please feel free to refer following link for more info,
https://in.mathworks.com/help/matlab/supportpkg/getting-started-with-matlab-support-package-for-arduino-hardware.html
Thanks
MATLAB Hardware Team
MathWorks

Products

Community Treasure Hunt

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

Start Hunting!