Matlab Serial using wrong frequency?

2 次查看(过去 30 天)
Hello there.
So im using matlab for reading an Arduino, which I have programmed for sending data at 50Hz (1 sample per 0.02 sec).
And the problem Im facing is that matlab is reading those samples too slow.
I made a simple script to check the time it takes to read one sample:
s = serial(seriallist,'BaudRate',9600,'Terminator','CR');
fopen(s);
% s.ReadAsyncMode = 'manual';
% readasync(s)
tic
linea = fscanf(s);
toc
It takes 1,98 seconds for reading and I dont really understand why.
I really want it to go at 50Hz since what Im attempting to do is to plot the data on real time using a while (1) loop, and the latency right now is too high for the application to run smoothly.
Thanks in advance.

回答(1 个)

Mark Sherstan
Mark Sherstan 2019-3-22
MATLAB is not great for communicating with Ardiuno real time, if I remember 50 Hz is pushing the bounderies. A couple things you can try to speed up your program:
  • Change Baud rate to 115200
  • Send data as bytes (Serial.write instead of Serial.print, depending on your data on the Ardiuno side you might need to cast the values)
  • Try sampling 100 or 1000 values and calculate the average sample rate. Sometimes acquiring the first data point is slower then the rest espcially if you have anything in your void setup.
  • Have you installed the hardware support packages for MATLAB or Simulink?
Not sure if you have written a real time plotting function so thought I would also include this for you:
function [] = realTimePlotter()
% Set up figure, get properties, and label
figure
h = animatedline;
ax = gca;
ax.YLim = [0 5];
xlabel('Time (s)')
ylabel('Output Y [units]')
% Start a timer
tic
startTime = toc;
% Loop for 20 secounds
while toc < 20
% Random data
v = randi(4);
% Get current time and add to animation
t = toc - startTime;
addpoints(h,t,v)
% Update axes
if t < 5
ax.XLim = [0 10];
drawnow
else
ax.XLim = [t-5 t+5];
drawnow
end
end

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by