% Code to plot simulation results from sdl_gear_backlash
%% Plot Description:
%
% The plot below shows the speed of two shafts connected by gears with
% backlash.  The input shaft is driven by a constant torque.  As the input
% gear strikes the output gear, each impact accelerates the output shaft.
% Eventually, the shafts spin at the same speed.

% Copyright 2016 The MathWorks, Inc.

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

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

% Get simulation results
simlog_t = simlog_sdl_gear_backlash.Inertia_Base.w.series.time;
simlog_wIn = simlog_sdl_gear_backlash.Inertia_Base.w.series.values('deg/s');
simlog_wOut = simlog_sdl_gear_backlash.Inertia_Follower.w.series.values('deg/s');
simlog_xBacklash = simlog_sdl_gear_backlash.Backlash.phi.series.values('deg');

% Plot results
%simlog_handles(1) = subplot(2, 1, 1);
yyaxis left
plot(simlog_t, simlog_wIn, 'LineWidth', 1)
hold on
plot(simlog_t, simlog_wOut, 'LineWidth', 1)
hold off
ylabel('Speed (deg/s)')
yyaxis right
plot(simlog_t, simlog_xBacklash, 'LineWidth', 1)
ylabel('Gap Angle (deg)')
grid on
title('Shaft Speed and Gap Angle')
legend({'Input Speed','Output Speed','Gap Angle'},'Location','Best');
xlabel('Time (s)')


% Remove temporary variables
clear simlog_t 
clear simlog_wIn simlog_wOut simlog_xBacklash

