% Code to plot simulation results from sdl_winch_with_brake
%% Plot Description:
%
% The plot below shows the position of a mass dragged across a floor by a
% winch. When the brake is applied, the mass stops moving.  This stalls the
% motor, increasing the amount of power it draws from its voltage source.

% Copyright 2016 The MathWorks, Inc.

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

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

% Get simulation results
simlog_t = simlog_sdl_winch_with_brake.Sensor_Mass.Motion_Sensor.x.series.time;
simlog_xMass = simlog_sdl_winch_with_brake.Sensor_Mass.Motion_Sensor.x.series.values('m');
simlog_iMotor = simlog_sdl_winch_with_brake.DC_Voltage.i.series.values('A');
simlog_vMotor = simlog_sdl_winch_with_brake.DC_Voltage.v.series.values('V');
simlog_pMotor = -simlog_iMotor.*simlog_vMotor;
simlog_fBrake = simlog_sdl_winch_with_brake.Brake.F.series.values('N');

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
yyaxis left
plot(simlog_t, simlog_xMass, 'LineWidth', 1)
ylabel('Position (m)');
yyaxis right
plot(simlog_t, simlog_pMotor, 'LineWidth', 1)
ylabel('Power (W)');
grid on
title('Mass Position and Motor Power')

simlog_handles(2) = subplot(2, 1, 2);
plot(simlog_t, simlog_fBrake, 'LineWidth', 1)
grid on
title('Brake Force')
ylabel('Force (N)')
xlabel('Time (s)')

linkaxes(simlog_handles, 'x')

% Remove temporary variables
clear simlog_t simlog_handles
clear simlog_xMass simlog_iMotor simlog_vMotor simlog_pMotor simlog_fBrake
