You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matlab中当值连续10秒未变化时终止数据采集循环?

Solution for Arduino Potentiometer Data Collection with Auto-Termination on Inactivity

Got it, let's work through this problem together. The core requirement is to stop collecting data early if the potentiometer stays still for 10 seconds, while also respecting the 2-minute maximum duration. Here's a step-by-step implementation in MATLAB:

Key Approach

We'll need to:

  1. Establish a connection to your Arduino and set up the analog input for the potentiometer.
  2. Track both the total elapsed collection time and the time since the potentiometer last changed.
  3. Check two termination conditions each loop: total time reaches 2 minutes, or the potentiometer has been static for 10 seconds.
  4. Save all collected data to an Excel file once collection stops.

Full MATLAB Code Implementation

% --------------------------
% Step 1: Initialize Arduino Connection
% --------------------------
% Replace COM port and board type with your actual setup
a = arduino('COM3', 'Uno'); 
potentiometerPin = 'A0'; % Analog pin connected to your potentiometer

% --------------------------
% Step 2: Configure Collection Parameters
% --------------------------
maxCollectionTime = 120;       % 2 minutes in seconds
inactivityThreshold = 10;      % Stop after 10 seconds of inactivity
valueChangeThreshold = 5;      % Ignore tiny fluctuations (adjust based on your pot)
sampleRate = 10;               % 10 samples per second (balances speed and data size)
sampleInterval = 1/sampleRate; % Time between samples

% Initialize data storage
collectedData = struct(
    'Timestamp', datetime.empty,
    'PotentiometerValue', double.empty
);
lastMovementTime = datetime('now'); % Track when the pot last changed
startTime = datetime('now');        % Track when collection started

% --------------------------
% Step 3: Data Collection Loop
% --------------------------
disp('Starting data collection...');
while true
    % Check if we've hit the maximum collection time
    elapsedTotalTime = seconds(datetime('now') - startTime);
    if elapsedTotalTime >= maxCollectionTime
        disp('Max collection time reached. Stopping.');
        break;
    end

    % Read current potentiometer value (0-1023 for analog pin)
    currentValue = readAnalogPin(a, potentiometerPin);

    % Save the current sample
    collectedData.Timestamp = [collectedData.Timestamp; datetime('now')];
    collectedData.PotentiometerValue = [collectedData.PotentiometerValue; currentValue];

    % Update last movement time if the pot changed significantly
    if length(collectedData.PotentiometerValue) > 1
        valueDifference = abs(currentValue - collectedData.PotentiometerValue(end-1));
        if valueDifference > valueChangeThreshold
            lastMovementTime = datetime('now');
        end
    end

    % Check if we've hit the inactivity threshold
    elapsedInactivityTime = seconds(datetime('now') - lastMovementTime);
    if elapsedInactivityTime >= inactivityThreshold
        disp(['Potentiometer inactive for ', num2str(inactivityThreshold), ' seconds. Stopping.']);
        break;
    end

    % Wait for the next sample interval
    pause(sampleInterval);
end

% --------------------------
% Step 4: Save Data to Excel
% --------------------------
% Convert collected data to a table for easy Excel writing
dataTable = table(
    collectedData.Timestamp,
    collectedData.PotentiometerValue,
    'VariableNames', {'Timestamp', 'Potentiometer_Value'}
);

% Write to Excel (will create file if it doesn't exist)
writetable(dataTable, 'potentiometer_collection_data.xlsx');
disp('Data successfully saved to potentiometer_collection_data.xlsx');

% Clean up Arduino connection
delete(a);

Important Notes & Adjustments

  • Port/Board Configuration: Make sure to update 'COM3' and 'Uno' to match your Arduino's actual port and model.
  • Value Change Threshold: The valueChangeThreshold = 5 ignores tiny electrical fluctuations in the potentiometer. If your pot is noisy, increase this value; if you need super-sensitive detection, decrease it.
  • Sample Rate: Adjust sampleRate if you need faster/slower sampling. Higher rates mean more data but more frequent checks for inactivity.
  • Voltage vs Raw Value: If you prefer to read voltage instead of the raw 0-1023 value, replace readAnalogPin with readVoltage.

内容的提问来源于stack exchange,提问作者Glu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:06:09