clear; clc;

try
    fprintf('Attempting to connect to Arduino...\n');
    portName = '/dev/cu.usbmodem141401'; 
    
    a = arduino(portName, 'Mega2560');
    
    fprintf('SUCCESS: Arduino connected on port %s\n', a.Port);
    fprintf('Board: %s\n', a.Board);

    fprintf('\nTesting potentiometer for 5 seconds...\n');
    fprintf('Turn the knob to see values change between 0-5V\n');
    
    figure('Name', 'Potentiometer Test', 'NumberTitle', 'off');
    h = plot(0, 0, 'b-', 'LineWidth', 2);
    xlabel('Time (s)');
    ylabel('Voltage (V)');
    title('Potentiometer Reading (Turn the Knob!)');
    grid on;
    ylim([0 5]);
    xlim([0 5]);
    timeData = [];
    voltageData = [];
    
    tic;    
    for i = 1:50 
        voltage = readVoltage(a, 'A0');
        currentTime = toc;
        
        fprintf('Time: %.1fs, Voltage: %.2f V\n', currentTime, voltage);
        timeData = [timeData, currentTime];
        voltageData = [voltageData, voltage];
        set(h, 'XData', timeData, 'YData', voltageData);
        drawnow;
        pause(0.1);
    end
    

    fprintf('\n=== Test Summary ===\n');
    fprintf('Duration: %.1f seconds\n', timeData(end));
    fprintf('Min voltage: %.2f V\n', min(voltageData));
    fprintf('Max voltage: %.2f V\n', max(voltageData));
    fprintf('Average voltage: %.2f V\n', mean(voltageData));
    
    %Save data to file
    data = table(timeData', voltageData', 'VariableNames', {'Time_s', 'Voltage_V'});
    writetable(data, 'potentiometer_test_data.csv');
    fprintf('Data saved to potentiometer_test_data.csv\n');
    
    clear a;
    fprintf('\nTest completed successfully!\n');
    
catch ME
    fprintf('ERROR: Failed during potentiometer test\n');
    fprintf('Error message: %s\n', ME.message);
    if exist('a', 'var')
        clear a;
    end
end