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

조회 수: 4 (최근 30일)
Hello,
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
clc
% 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
pause(pauseTime);
%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
pause(pauseTime)
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
pause(pauseTime)
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
pause(pauseTime);
plot(photoResistor(:,1),'r');hold on;
plot(photoResistor(:,2),'g');hold on
plot(photoResistor(:,3),'b');
legend('Red', 'Green', 'Blue');hold off;
end
writePWMVoltage(a,'D3',5); % Red
writePWMVoltage(a,'D5',5); % Green
writePWMVoltage(a,'D6',5); %Blue
clear a %Disconnect from Arduino

채택된 답변

Amrtanshu Raj
Amrtanshu Raj 2021년 4월 23일
Hi,
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 !!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Arduino Hardware에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by