Created
December 6, 2023 14:48
-
-
Save ashwanirathee/f6d3e14a5f52f00e371387b1fc3caf00 to your computer and use it in GitHub Desktop.
RC Circuits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Revise | |
using ModelingToolkit | |
using ModelingToolkitStandardLibrary.Blocks: RealInput, Step, Sine, Cosine | |
using ModelingToolkitStandardLibrary.Electrical | |
using OrdinaryDiffEq | |
using Plots | |
@parameters t | |
@component function ControlledSwitch(; name) | |
@named n = Pin() | |
@named p = Pin() | |
@named u = RealInput() | |
eqs = [ 0 ~ ifelse(u.u > 0.05, n.v - p.v, n.i) | |
0 ~ ifelse(u.u > 0.05, n.i + p.i, p.i) | |
] | |
ODESystem(eqs, t, [], []; name, systems=[p, n, u]) | |
end | |
function plot_controlled_switch() | |
@named vcc = Voltage() | |
@named resistor = Resistor(R=1) | |
@named resistor2 = Resistor(R=0.0001) | |
@named resistor3 = Resistor(R=0.0001) | |
@named cap = Capacitor(C=4) | |
@named ground = Ground() | |
@named switch1 = ControlledSwitch() | |
@named control1 = Cosine(;frequency = 0.01) | |
@named switch2 = ControlledSwitch() | |
@named control2 = Cosine(;frequency = 0.01, phase = π) | |
ps = @parameters supply_voltage=12.0 | |
eqs = [ | |
connect(vcc.p, resistor2.p) | |
connect(resistor2.n, switch1.p) | |
connect(switch1.n, resistor.p) | |
connect(switch2.n, resistor.p) | |
connect(resistor.n, cap.p) | |
connect(switch2.p, resistor3.p) | |
connect(vcc.n, resistor3.n, cap.n, ground.g) | |
vcc.V.u ~ supply_voltage | |
connect(switch1.u, control1.output) | |
connect(switch2.u, control2.output) | |
] | |
@named switch_sys = ODESystem(eqs, t, [], ps; | |
systems = [vcc, resistor2, resistor, resistor3, switch1, switch2, cap, ground, control1, control2]) | |
sys = structural_simplify(switch_sys) | |
prob = ODAEProblem(sys, [], (0, 200.0)) | |
sol = solve(prob, Tsit5()) | |
plot(sol, idxs = [cap.v, resistor.i, control1.output.u>0.05, control2.output.u > 0.05], | |
title = "RC charging and Discharging!", | |
labels = ["Capacitor Voltage(V)" "Resistor Current(A)" "Switch 1 state" "Switch 2 state"]) | |
end | |
plot_controlled_switch() |
Author
ashwanirathee
commented
Dec 6, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment