В следующем примере показан линейный резистор с дополнительным тепловым портом. Компонент использует условные секции для реализации логики управления. annotations разделы в условных ветвях выборочно отображают или скрывают соответствующие порты, параметры и переменные на основе значения параметра управления. Два варианта блоков имеют разное количество портов, и поэтому значок пользовательского блока также изменяется соответствующим образом.
component CondResistor
% Linear Resistor with Optional Thermal Port
% If "Model thermal effects" is set to "Off", the block represents a
% linear resistor. The voltage-current (V-I) relationship is V=I*R,
% where R is the constant resistance in ohms.
%
% If "Model thermal effects" is set to "On", the block represents a
% resistor with a thermal port. The resistance at temperature T1 is given by
% R(T) = R0*(1+alpha(T1-T0)), where R0 is the Nominal resistance at the
% Reference temperature T0, and alpha is the Temperature coefficient.
nodes
p = foundation.electrical.electrical; % +:left
n = foundation.electrical.electrical; % -:right
H = foundation.thermal.thermal; % H:left
end
parameters
thermal_effects = simscape.enum.onoff.off; % Model thermal effects
end
parameters(ExternalAccess=none)
R = { 1, 'Ohm' }; % Nominal resistance
T0 = {300,'K'}; % Reference temperature
alpha = {50e-6,'1/K'}; % Temperature coefficient
tc = {10,'s'}; % Thermal time constant
K_d = {1e-3,'W/K'}; % Dissipation factor
end
variables(ExternalAccess=none)
i = { 0, 'A' }; % Current
v = { 0, 'V' }; % Voltage
T1 = {value = {300,'K'}, priority = priority.high}; % Temperature
end
branches
i : p.i -> n.i;
end
equations
v == p.v - n.v;
end
if thermal_effects == simscape.enum.onoff.off
annotations
% Show non-thermal settings
Icon = 'custom_resistor.png';
[R, i, v] : ExternalAccess=modify;
% Hide thermal node
H : ExternalAccess=none;
end
connections
connect(H, *); % Connect hidden thermal node to reference
end
equations
R*i == v;
T1 == T0; % Temperature is constant
end
else
annotations
% Show thermal settings
Icon = 'custom_resistor_thermal.png';
[T1, T0, alpha, tc, K_d, H] : ExternalAccess=modify;
end
% Add heat flow + thermal equations
variables(Access=private)
Q = { 0, 'J/s' }; % Heat flow
end
branches
Q : H.Q -> *
end
equations
T1 == H.T;
let
mc = tc*K_d; % mc in Q = m*c*dT
% Calculate R(T), protecting against negative values
Rdem = R*(1+alpha*(T1-T0));
R_T = if Rdem > 0, Rdem else {0,'Ohm'} end;
in
R_T*i == v; % Electrical equation
mc * T1.der == Q + R_T*i*i; % Thermal equation
end
end
end
end
Компонент первоначально объявляет все необязательные параметры и переменные с помощью ExternalAccess атрибут имеет значение none, а затем предоставляет их выборочно с помощью условного annotations разделы. Также допустим и противоположный метод скрытия неприменимых элементов, но этот подход легче масштабировать при наличии нескольких конфигураций компонентов.
Если для параметра управления «Тепловые эффекты модели» задано значение Offблок представляет линейный резистор. Единственным открытым параметром блока является Номинальное сопротивление (Nominal resistance), вкладка Переменные (Variables) позволяет задать целевые значения тока и напряжения, а значок блока имеет два порта, + и -.



Если для параметра Тепловые эффекты модели (Model thermal effects) задано значение On, блок представляет собой резистор с тепловым портом, с зависящим от температуры сопротивлением. Параметры блока, переменные, порты и значки пользовательских блоков изменяются соответствующим образом.


