clear; clc; close all; %% Parametros puerto = 'COM6'; baudrate = 9600; %% Crear objeto serial (API vieja) s = serial(puerto, 'BaudRate', baudrate); % Configurar terminador set(s, 'Terminator', 'LF'); %% Abrir puerto fopen(s); pause(2); % esperar reinicio Arduino fprintf('Adquiriendo... (cerrar figura para detener)\n'); %% Inicializar tiempo_ms = []; peso_g = []; %% Figura fig = figure; hold on; grid on; xlabel('Tiempo (s)'); ylabel('Peso (g)'); title('Lectura en tiempo real'); %% Loop while ishandle(fig) if s.BytesAvailable > 0 linea = fgetl(s); % equivalente a readline datos = strsplit(linea, ','); if numel(datos) == 2 t = str2double(datos{1}); p = str2double(datos{2}); if ~isnan(t) && ~isnan(p) tiempo_ms(end+1) = t; peso_g(end+1) = p; plot(t/1000, p, '.b'); drawnow; end end end end fprintf('Adquisicion detenida.\n'); %% Cerrar puerto fclose(s); delete(s); clear s; %% Procesar tiempo_s = tiempo_ms / 1000; %% Grafico final figure; plot(tiempo_s, peso_g, '.-'); xlabel('Tiempo (s)'); ylabel('Peso (g)'); title('Datos finales'); grid on; %% Guardar timestamp = datestr(now, 'yymmdd_HHMM'); filename = ['datos_balanza_' timestamp '.mat']; save(filename, 'tiempo_s', 'peso_g'); fprintf('Datos guardados en %s\n', filename);