And a more complete example just for fun.
using Revise
using ModelingToolkit
using ModelingToolkitStandardLibrary.Blocks: RealInput, Step
using ModelingToolkitStandardLibrary.Electrical
using OrdinaryDiffEq
using Plots
@parameters t
@component function IdealSwitch(; name, isClosed=true)
@named n = Pin()
@named p = Pin()
ps = @parameters isClosed=isClosed
eqs = [ 0 ~ ifelse(isClosed == true, n.v - p.v, n.i)
0 ~ ifelse(isClosed == true, n.i + p.i, p.i)
]
ODESystem(eqs, t, [], ps; name, systems=[p, n])
end
"""
A switch whose state is controlled by a RealInput pin.
The switching threshold is 0.5, open when input is less closed when input is greater.
"""
@component function ControlledSwitch(; name)
@named n = Pin()
@named p = Pin()
@named u = RealInput()
eqs = [ 0 ~ ifelse(u.u > 0.5, n.v - p.v, n.i)
0 ~ ifelse(u.u > 0.5, n.i + p.i, p.i)
]
ODESystem(eqs, t, [], []; name, systems=[p, n, u])
end
function plot_ideal_switch(;isClosed=true)
@named vcc = Voltage()
@named resistor = Resistor(R=2)
@named switch = IdealSwitch(;isClosed)
@named ground = Ground()
ps = @parameters supply_voltage=12.0
eqs = [
connect(vcc.p, resistor.p)
connect(resistor.n, switch.p)
connect(vcc.n, switch.n, ground.g)
vcc.V.u ~ supply_voltage
]
@named switch_sys = ODESystem(eqs, t, [], ps;
systems = [vcc, resistor, switch, ground])
sys = structural_simplify(switch_sys)
prob = ODAEProblem(sys, [], (0, 10.0))
sol = solve(prob, Tsit5())
plot(sol, idxs = [resistor.v, resistor.i],
title = "Switch Demonstration",
labels = ["Resistor Voltage" "Resistor Current"])
end
"""
With no dynamics (no time-derivative terms), no time stepping is performed.
This example adds a parallel RC circuit some stepping happens and the switch
time can be plotted.
'"""
function plot_controlled_switch()
@named vcc = Voltage()
@named resistor = Resistor(R=2)
@named r2 = Resistor(R=75e3)
@named cap = Capacitor(C=10e-6)
@named switch = ControlledSwitch()
@named ground = Ground()
@named control = Step(;start_time=5.0)
ps = @parameters supply_voltage=12.0
eqs = [
connect(vcc.p, resistor.p, r2.p)
connect(resistor.n, switch.p)
connect(r2.n, cap.p)
connect(vcc.n, switch.n, cap.n, ground.g)
vcc.V.u ~ supply_voltage
connect(switch.u, control.output)
]
@named switch_sys = ODESystem(eqs, t, [], ps;
systems = [vcc, resistor, switch, r2, cap, ground, control])
sys = structural_simplify(switch_sys)
prob = ODAEProblem(sys, [], (0, 10.0))
sol = solve(prob, Tsit5())
plot(sol, idxs = [resistor.v, resistor.i, control.output.u],
title = "Switch Demonstration",
labels = ["Resistor Voltage" "Resistor Current" "Switch"])
end