% Code to plot simulation results from sdl_ratchet_leadscrew
%% Plot Description:
%
% The plot below shows the speed of the input shaft, leadscrew nut, and the
% motion of the screw.  The self-locking behavior of the leadscrew plus the
% unidirectional clutch enables the cyclical input motion to move the screw
% in a single direction.

% Copyright 2016 The MathWorks, Inc.

% Generate simulation results if they don't exist
if ~exist('simlog_sdl_ratchet_leadscrew', 'var')
    sim('sdl_ratchet_leadscrew')
end

% Reuse figure if it exists, else create new figure
if ~exist('h1_sdl_ratchet_leadscrew', 'var') || ...
        ~isgraphics(h1_sdl_ratchet_leadscrew, 'figure')
    h1_sdl_ratchet_leadscrew = figure('Name', 'sdl_ratchet_leadscrew');
end
figure(h1_sdl_ratchet_leadscrew)
clf(h1_sdl_ratchet_leadscrew)

% Get simulation results
simlog_t = simlog_sdl_ratchet_leadscrew.Inertia_Shaft.w.series.time;
simlog_wShaft = simlog_sdl_ratchet_leadscrew.Inertia_Shaft.w.series.values('rad/s');
simlog_wNut = simlog_sdl_ratchet_leadscrew.Inertia_Nut.w.series.values('rad/s');
simlog_xMass = simlog_sdl_ratchet_leadscrew.Sensor_Mass.Motion_Sensor.x.series.values('mm');
simlog_tShaft = simlog_sdl_ratchet_leadscrew.Velocity_Source.t.series.values('N*m');

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
yyaxis left
plot(simlog_t, simlog_wShaft, 'LineWidth', 1)
ylabel('Speed deg/s')
hold on
plot(simlog_t, simlog_wNut,'--','LineWidth', 2)
hold off
yyaxis right
plot(simlog_t, simlog_xMass,'LineWidth', 1)
ylabel('Position (cm)')
grid on
title('Speed and Position')
legend({'Input','Nut','Screw'},'Location','Best');

simlog_handles(2) = subplot(2, 1, 2);
plot(simlog_t, simlog_tShaft, 'LineWidth', 1)
grid on
title('Input Torque')
ylabel('Torque (N*m)')
xlabel('Time (s)')

linkaxes(simlog_handles, 'x')

% Remove temporary variables
clear simlog_t simlog_handles
clear simlog_wShaft simlog_wNut simlog_xMass simlog_tShaft
