Need help to see if the two codes I fused together are correctly placed

6 次查看(过去 30 天)
clear all; close all;
a = arduino('/dev/tty.SLAB_USBtoUART', 'uno')
tic
max_samples = 1000;
tic
for i = 1:max_samples
sound_data(i) = readVoltage(a,'A2')
time_data(i) = toc;
end
plot(time_data, sound_data)
figure
h = animatedline;
ax = gca;
ax.YGrid = 'on';
ax.YLim = [-0.1 5];
title('Sound sensor voltage vs time (live)');
ylabel('Time [HH:MM:SS]');
xlabel('Voltage [volt]');
stop = false;
startTime = datetime('now');
while ~stop
voltage = readVoltage(a,'A2');
t = datetime('now') - startTime;
addpoints(h,datenum(t),voltage)
ax.XLim = datenum([t-seconds(15) t]);
datetick('x','keeplimits')
drawnow
stop = readDigitalPin(a,'D6');
end

回答(1 个)

Abhipsa
Abhipsa 2025-9-2,3:34
The combined code looks almost correct, but it requires some minor changes.
  • "tic" is called twice, only one is needed before the 1000-sample loop.
  • "sound_data(i) = readVoltage" is missing a semicolon which can spam the Command Window.
  • Pre-allocate "sound_data/time_data" so the loop doesn’t grow arrays.
  • Your first plot uses seconds on the x-axis, but the live plot uses "datenum"—mixing styles isn’t necessary. Use elapsed seconds for both.
  • Add simple debouncing so a noisy button doesn’t stop the loop immediately.
clearvars; close all; clc
% 1) Connect to Arduino / Grove
a = arduino('/dev/tty.SLAB_USBtoUART','uno'); % adjust port if needed
configurePin(a,'D6','DigitalInput'); % stop button
% 2) Capture 1000 samples
max_samples = 1000;
sound_data = zeros(1,max_samples);
time_data = zeros(1,max_samples);
tic; % start timer
for i = 1:max_samples
sound_data(i) = readVoltage(a,'A2'); % Grove sound sensor on A2
time_data(i) = toc; % seconds since tic
end
figure;
plot(time_data, sound_data, 'LineWidth', 1);
grid on
xlabel('Time [s]');
ylabel('Voltage [V]');
title('Captured sound (1000 samples)');
% 3) Live feed until button D6 is pressed
figure
h = animatedline('LineWidth',1);
ax = gca; ax.YGrid = 'on'; ax.YLim = [-0.1 5];
xlabel('Time [s]'); ylabel('Voltage [V]');
title('Sound sensor voltage vs time (live)');
tic; % new timer for live view
stop = false;
lastPressT = -Inf; % for debounce
DEBOUNCE = 0.15; % seconds
while ~stop
v = readVoltage(a,'A2');
t = toc;
addpoints(h, t, v)
% show last 15 s
xlim([max(0, t-15), t])
drawnow limitrate
% --- Stop condition on D6 (adjust logic if using pull-down) ---
btn = readDigitalPin(a,'D6'); % HIGH when pressed with pull-up
if btn && (t - lastPressT) > DEBOUNCE
stop = true;
lastPressT = t;
end
end
I hope this helps you.

类别

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

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by