%% Sample BUMPTEST Modeling
%
%% Load sample data from MAT files
% load('data_bumptest_wl.mat');
% load('data_bumptest_Vm.mat');
%
%% Load variables
t = wl(:,1);
wl_meas = wl(:,2);
vm = Vm(:,2);
% Min/max voltage (V)
vm_min = min(vm);
vm_max = max(vm);
% Min/max times (s)
t_min = min(t);
t_max = max(t);
%
%% Plot response
subplot(2,1,1)
plot(t,wl_meas);
axis([t_min t_max 0 1.25*max(wl_meas)]);
ylabel('\omega_l (rad/s)');
subplot(2,1,2)
plot(t,vm);
axis([t_min t_max 0 5]);
ylabel('V_m (V)');
xlabel('time (s)')
%
%% Find model gain
% Initial velocity (rad/s)
wl_0 = min(wl_meas);
% Steady-state velocity (rad/s)
wl_ss = max(wl_meas);
% Input voltage step amplitude (V)
Av = vm_max - vm_min;
% Experimentally derived steady-state gain (rad/s/V)
Ke_b = (wl_ss - wl_0)/Av;
%
%% Find model time constant
% Load speed at first decay time (rad/s)
wl_t1 = (1-exp(-1))*wl_ss;
% Number of samples
N = max(size(vm));
% Initialize index
i = 1;
% Intialize flag
find_t1 = 0;
%
% While loop to find initial step time t0 and first decay time t1
while (i < N) && (find_t1 < 2)
    vm_last = vm(i);
    i = i + 1;
    % Step start time (s)
    if ( find_t1 == 0 ) && ( vm(i) > vm_last )
        t0 = t(i);
        find_t1 = 1;
    end
    % Find time of first decay (s)
    if ( find_t1 == 1) && ( wl_meas(i) > wl_t1 )
        t1 = t(i);
        find_t1 = 2; % indicates that t1 is found
    end
end
%
% Experimentally derived time constant (s)
tau_e_b = t1 - t0;
%
%% Display
disp( 'SRV02 model parameters derived using bumptest: ' )
disp( [ '   Ke_b = ' num2str( Ke_b, 3 ) ' rad/s/V' ] )
disp( [ '   tau_e_b = ' num2str( tau_e_b, 3 ) ' s' ] )