Time Lag between Arduino and Matlab for Live data plotting
11 ビュー (過去 30 日間)
古いコメントを表示
Hi everyone,
I'm plotting live sine wave data from arduino to MATLAB using serial communication. The sine wave plots great, however there is a lag/noise at the start of the live plotting and not quite sure why it's happening. I've added a delay in arduino IDE to allow time for serial communication and a delay in matlab to allow time for the plot to update but not quite sure why it's happening. Any help is appreciated.
The error at the start of the plot is shown below:
Matlab Code:
delete(instrfindall);
clc;
serialPort = 'COM4';
plotTitle = 'Sine Wave';
xLabel = 'Time (s)';
yLabel = 'Data';
plotGrid = 'on';
min = -1.5;
max = 1.5;
delay = .01;
%Define Function Variables
time = 0;
data = 0;
count = 0;
%Set up Plot
plotGraph = plot(time,data,'-r');
title(plotTitle,'FontSize',18);
xlabel(xLabel,'FontSize',15);
ylabel(yLabel,'FontSize',15);
axis([0 10 min max]);
grid(plotGrid);
%Open Serial COM Port
s= serial(serialPort);
disp('Close Plot to clear data');
fopen(s);
% start stopwatch timer
tic
%Loop when Plot is Active
while time <=50
%Read Data from Serial as Float
dat = fscanf(s,'%f');
if(~isempty(dat) && isfloat(dat)) %Make sure Data Type is Correct
count = count + 1;
time(count) = toc; %stop the stopwatch and extract time
data(count) = dat(1); %Extract 1st Data Element
set(plotGraph,'XData',time,'YData',data);
axis([0 time(count) min max]);
end
%Allow MATLAB to Update Plot
pause(delay);
end
%Close Serial COM Port and Delete useless Variables
fclose(s);
flushinput(serialPort);
clear count dat delay max min plotGraph plotGrid plotTitle s ...
scrollWidth serialPort xLabel yLabel;
Arduino Code:
double x = 0;
void setup() {
Serial.begin(9600);
x = 0;
}
void loop() {
Serial.flush();
Serial.println(sin(x));
x += .05;
if(x >= 2*3.14)
x = 0;
//Allow Time to Process Serial Communication
delay(50);
}
0 件のコメント
回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!