%% Simulate Chart as a Simulink Block With Temporal Conditions
% This example provides another alternative for modeling the transmission
% system in a car. The Stateflow chart appears as a block in a Simulink model. The
% other blocks in the model represent related automotive components. The
% chart interfaces with the other blocks by sharing data through input and
% output connections. To open the chart, click the arrow in the bottom left
% corner of the |Gear_logic| block.

% Copyright 2009-2020 The MathWorks, Inc.

%%

model = 'sf_car_using_duration';
load_system(model);

% Delete all annotations at the top level of the model
ah = find_system(model, 'FindAll', 'on', 'type', 'annotation');
for i = 1:length(ah)
   ao = get_param(ah(i), 'Object');
   ao.delete;
end

open_system(model);
close_system([model '/Scope'])

%%
% This chart combines state hierarchy, active state data, and
% temporal logic.
%
% * *Hierarchy:* This model places the four-speed automatic transmission
% chart inside a superstate |gear|. The superstate monitors the vehicle and
% engine speeds and triggers gear changes. The actions listed on the upper
% left corner of the state gear determine the operating thresholds for the
% selected gear and the values of the Boolean conditions |up| and |down|.
% The label |en,du| indicates that the state actions are executed when the
% state first becomes active (|en| = |entry|) and at every subsequent time
% step while the state is active (|du| = |during|).
% * *Active State Data:* The output value |gear| reflects the choice of
% gears during simulation. The chart generates this value from the active
% substate in |gear|.
% * *Temporal Logic:* To prevent a rapid succession of gear changes, the
% Boolean conditions |up| and |down| use the temporal logic operator
% |<docid:stateflow_ref#duration duration>| to control the transition
% between gears. The conditions are valid when the speed of the car remains
% outside the range of operation for the selected gear longer than some
% predetermined time |TWAIT| (measured in seconds).

% Set up charts with white background
set_param(0,'ExportBackgroundColorMode','white');

open_system([model '/Gear_logic'],'force')

%%
% To run a simulation of the model:
% 
% # Double-click the *User Inputs* block. In the Signal Builder dialog
% box, you can select a predefined brake-to-throttle profile to simulate or
% create a custom profile. The default profile is |Passing Maneuver|.
% # Click *Run*. In the Stateflow Editor, chart animation highlights the
% active states during the simulation. To slow down the animation, in the
% *Debug* tab, select |Slow| from the *Animation Speed* drop-down list.
% # In the Scope block, examine the results of the simulation. The scope
% displays a graph of the gear selected during simulation.

sim(model)
open_system([model '/Scope'])