Is it possible to control/read Arduino pins at different frequencies?

5 views (last 30 days)
The attached code is meant to flash an RGB LED and record data from a photoresistor. Currently, the code flashes the LED on one line, and then records data from the analog chanel on the next line. Ideally, I would like to have parallel code that flashes the LEDs based on a specific duty cycle (e.g. 6 Hz flashes cycling red, green, and blue) but a higher sampling frequency for the photoresistor analog chanel (e.g. 30 Hz). Is this possible within MATLAB's paradigm of sequential code execution?
Thanks in advance.
%% Arduino RGB LED Control%%
clear all
% Create an arduino object
a = arduino();
% Collection parameters
cycles = 10;
flashTime = .1;
pauseTime = .1;
photoResistor = zeros(cycles,3);
% Configure and pulse LED based on collection parameters
writePWMVoltage(a,'D3',5); % Red
writePWMVoltage(a,'D5',5); % Green
writePWMVoltage(a,'D6',5); % Blue
for i = 1:cycles
%Flash Red
writePWMVoltage(a,'D3',0); % Red
writePWMVoltage(a,'D5',5); % Green
writePWMVoltage(a,'D6',5); % Blue
pause(flashTime); photoResistor(i,1) = readVoltage(a, 'A0');
writePWMVoltage(a,'D3',5); % Red
writePWMVoltage(a,'D3',5); % Red
writePWMVoltage(a,'D5',0); % Green
writePWMVoltage(a,'D6',5); %Blue
pause(flashTime); photoResistor(i,2) = readVoltage(a, 'A0');
writePWMVoltage(a,'D5',5); % Green
writePWMVoltage(a,'D3',5); % Red
writePWMVoltage(a,'D5',5); % Green
writePWMVoltage(a,'D6',0); %Blue
pause(flashTime); photoResistor(i,3) = readVoltage(a, 'A0');
writePWMVoltage(a,'D6',5); % Blue
plot(photoResistor(:,1),'r');hold on;
plot(photoResistor(:,2),'g');hold on
legend('Red', 'Green', 'Blue');hold off;
writePWMVoltage(a,'D3',5); % Red
writePWMVoltage(a,'D5',5); % Green
writePWMVoltage(a,'D6',5); %Blue
clear a %Disconnect from Arduino

Accepted Answer

Amrtanshu Raj
Amrtanshu Raj on 23 Apr 2021
Parallel computation or multithreading is not supported by Arduino so flashing the LED and reading the Photo Resistor at different frequency would not be possible.
However I can think of a work around, if you try to implement the logic such that
  1. Have a main loop without any delays.
  2. Read the photoresistor at every loop.
  3. Store the time stamp every time the led was switched/changed in a variable.
  4. Switch/toggle the led when the (current time - last time > threshold).
This is obviously not multi threading but since the execution frequency is high enough, it can be considered almost parallel for practical purpose.
Hope this helps !!

More Answers (0)


Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!