How do I change the sample rate of the animated line

3 次查看(过去 30 天)
I've got an arduino that is sending a signal to Matlab. The current code I have plots the signal but it's obscured due to the sampling rate. How do I implement or change the sampling rate. This is the code I use to obtain data from the arduino:
figure
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.YLim = [0 2];
stop = false;
startTime = datetime('now');
while ~stop
v = readVoltage(a,'A5');
output = v
time = datetime('now') - startTime;
addpoints(h,datenum(time),output)
ax.XLim = datenum([time-seconds(50) time]);
datetick('x','keeplimits')
drawnow
stop = readDigitalPin(a, 'A6');
end

回答(1 个)

Walter Roberson
Walter Roberson 2018-10-30
You need to redesign your code to overcome this. You need to create an arduino sketch or c/c++ program that does nothing other than to reads the pins and send the results to MATLAB.
Note that if you are using the USB port to send the data then it is limited in the number of transactions per second. https://www.mathworks.com/matlabcentral/answers/400467-what-is-matlab-s-sampling-rate-through-arduino-analog-input#comment_567391
  2 个评论
Mark Rodger
Mark Rodger 2018-11-8
Thanks for the comment, I've managed to program the arduino to sample at a rate of 50Hz. In Matlab its 100Hz to prevent delays. I'm able to plot the acquired data in a figure. I would now like to plot the data in real time by using animated line but I have this error: Index exceeds matrix dimensions. Error in ANI_DAT_TEST (line 23) addpoints(h,data(i),t(i));
Do you have any suggestions?
This the code I'm using:
% code
ar = serial('COM6','BaudRate',9600);
try
fopen(ar);
catch err
fclose(instrfind);
error('Make sure you select the correct COM Port where the Arduino is connected.');
end
Tmax = 100; % Total time for data collection (s)
Ts = 0.01; % Sampling time (s), it correspond to 100Hz
i = 0;
data = 0;
t = 0;
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.YLim = [0 2];
tic % Start time
while toc <= Tmax
i = i + 1;
% Fill the data matrix with the data read from arduino
data(i) = fscanf(ar,'%d');
addpoints(h,data(i),t(i));
% If matlab read the data faster than the sampling rate set in arduino, force sampling to be the same as the
% sampling time set in matpab code, If matlab is reading slower, nothing can be done.
t(i) = toc;
if i > 1
T = toc - t(i-1);
while T < Ts
T = toc - t(i-1);
end
end
t(i) = toc;
end
fclose(ar);
end
Walter Roberson
Walter Roberson 2018-11-8
You do not set t(i) until after you addpoint trying to use its value.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Arduino Hardware 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by