
What can I add in this code for me to plot the data that I obtained in real time graph?
5 次查看(过去 30 天)
显示 更早的评论
function [] = i2c_sensor()
a = arduino('COM3', 'UNO');
imu = mpu6050(a,'SampleRate',50,'SamplesPerRead',10,'ReadMode','Latest');
for i=1:10
accelReadings = readAcceleration(imu);
display(accelReadings);
pause(1);
end
end
0 个评论
回答(1 个)
Aashray
2025-6-25
If you would like to visualize the accelerometer data from your “i2c_sensor()” function in real time, you can use MATLAB’s “animatedline” function to plot the data as it streams in.
Here is an example using simulated data. You can apply the same structure using your actual MPU6050 readings.
function [] = simulate_mpu6050_plot()
% Simulate 3-axis acceleration readings over time
% Set simulation parameters
numReadings = 100; % Number of data points to simulate
sampleRate = 10; % Hz (i.e., 1 reading every 0.1 seconds)
% Create animated lines for X, Y, Z axes
figure;
hX = animatedline('Color', 'r', 'DisplayName', 'X-axis');
hY = animatedline('Color', 'g', 'DisplayName', 'Y-axis');
hZ = animatedline('Color', 'b', 'DisplayName', 'Z-axis');
legend;
xlabel('Time (s)');
ylabel('Acceleration (m/s^2)');
title('Simulated Real-Time Accelerometer Readings');
grid on;
% Initialize timer
tStart = tic;
for i = 1:numReadings
% Simulate random but smooth acceleration data
ax = 0.1*randn() + 0; % Simulate X-axis noise
ay = 0.1*randn() + 0; % Simulate Y-axis noise
az = 0.1*randn() + 9.81; % Simulate Z-axis around gravity
t = toc(tStart);
% Add simulated data points to animated lines
addpoints(hX, t, ax);
addpoints(hY, t, ay);
addpoints(hZ, t, az);
drawnow limitrate % Efficient plot update
pause(1 / sampleRate);
end
end
To use real sensor data, replace the random values (ax, ay, az) with the actual output of your sensor like this:
accel = readAcceleration(imu);
ax = accel(1); ay = accel(2); az = accel(3);
The plot should look similar to the one shown in the attached screenshot.

For more details, refer to the "animatedline" documentation:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Axes Appearance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!