Wednesday, December 2, 2026

Making Engineering Fun with Julia: An Interactive RLC Circuit Simulator...

Electrical / Electronics engineering becomes much more interesting when we can see equations come alive.

Recently, I developed an interactive Series RLC Circuit Transient Simulator using Julia and GLMakie. The application allows us to change resistance, inductance, and capacitance through sliders and observe how these parameters influence the circuit's transient response.

The project combines circuit theory, numerical methods, and interactive visualization in a single application.

Watch...



The Mathematics Behind the Circuit

A series RLC circuit consists of a resistor, an inductor, and a capacitor connected in series. When a DC step voltage is applied, the circuit current and capacitor voltage evolve over time.

Using Kirchhoff's Voltage Law:

$$ V_s = Ri + L\frac{di}{dt} + V_c $$

The capacitor relationship is:

$$ i = C\frac{dV_c}{dt} $$

These equations can be expressed as a system of first-order differential equations:

$$ \frac{di}{dt} = \frac{V_s - Ri - V_c}{L} $$ $$ \frac{dV_c}{dt} = \frac{i}{C} $$

The simulator uses these equations to calculate the circuit's behavior at every time step.

Enter Runge–Kutta: Solving Differential Equations Numerically

Many engineering systems are described by differential equations that are difficult or inconvenient to solve analytically. Numerical methods provide a way to approximate their solutions.

This project uses the fourth-order Runge–Kutta method (RK4).

The simplest numerical method, Euler's method, estimates the next value using the slope at the beginning of a time interval. RK4 improves this estimate by evaluating the slope four times:

  • (k_1): slope at the beginning of the interval

  • (k_2): slope at the midpoint, using the first estimate

  • (k_3): another midpoint estimate

  • (k_4): slope at the end of the interval

The weighted average of these four slopes gives the next state:

$$ x_{n+1} = x_n + \frac{\Delta t}{6} \left(k_1 + 2k_2 + 2k_3 + k_4\right) $$

In our simulator, the state vector is:

$$ x = \begin{bmatrix} i \\ V_c \end{bmatrix} $$

It contains the circuit current and capacitor voltage. RK4 advances both quantities together through time.

The simulation uses a time step of (10^{-5}) seconds. A sufficiently small time step helps capture the rapid changes that occur during the transient response.

What Can We Observe?

The application presents four engineering plots:

  1. Capacitor voltage — how the capacitor charges and approaches its steady-state voltage.

  2. Circuit current — how current rises, oscillates, and eventually settles.

  3. Component voltages — the voltage drops across the resistor, inductor, and capacitor.

  4. Stored energy — how energy moves between the inductor's magnetic field and the capacitor's electric field.

The component-voltage plot demonstrates Kirchhoff's Voltage Law:


V_r+V_l+V_c=V_s

The energy plot is particularly interesting. The inductor stores magnetic energy, while the capacitor stores electric energy:

$$ E_L = \frac{1}{2}Li^2 $$ $$ E_C = \frac{1}{2}CV_c^2 $$

The total stored energy changes as the circuit responds to the input, while the resistor dissipates energy as heat.

Interactive Engineering with Julia

The real excitement begins when we move the sliders.

Changing resistance affects damping. Changing inductance or capacitance changes the natural frequency of the circuit. The simulator recalculates the response and updates the plots dynamically.

Julia makes this kind of project approachable because its mathematical syntax closely resembles the equations we write on paper. With GLMakie, we can connect numerical calculations to interactive graphical elements without building a separate application in another language.

From Circuit Theory to Scientific Computing

This small project demonstrates a powerful idea: engineering concepts can be explored through computation rather than only through textbook examples.

The same approach can be extended to:

  • Parallel RLC circuits

  • Resonance and frequency response

  • PID control systems

  • Mechanical spring-mass-damper systems

  • Heat transfer and fluid simulation

A few equations, a numerical solver, and an interactive interface can turn an abstract engineering topic into a virtual laboratory.

For me, this is one of the most enjoyable aspects of scientific computing with Julia — the ability to experiment with mathematics and immediately see the physical consequences of changing a parameter.

Source Code...


using GLMakie

############################
# 1. Simulation Parameters & ODE
############################

Vs = 10.0           # DC step voltage (Volt)
t_start = 0.0
t_end = 0.1
dt = 1e-5

t = collect(t_start:dt:t_end)
t_ms = t .* 1000.0

function rlc_derivatives(x, R, L, C, Vs)
    current = x[1]
    voltage = x[2]
    di_dt = (Vs - R * current - voltage) / L
    dVc_dt = current / C
    return [di_dt, dVc_dt]
end

function rk4_step(x, dt, R, L, C, Vs)
    k1 = rlc_derivatives(x, R, L, C, Vs)
    k2 = rlc_derivatives(x .+ 0.5 * dt .* k1, R, L, C, Vs)
    k3 = rlc_derivatives(x .+ 0.5 * dt .* k2, R, L, C, Vs)
    k4 = rlc_derivatives(x .+ dt .* k3, R, L, C, Vs)
    return x .+ (dt / 6.0) .* (k1 .+ 2.0 .* k2 .+ 2.0 .* k3 .+ k4)
end

function simulate_rlc(t, R, L, C, Vs)
    N = length(t)
    step_dt = t[2] - t[1]
    i = zeros(N)
    Vc = zeros(N)
    x = [0.0, 0.0]

    for k in 1:N
        i[k] = x[1]
        Vc[k] = x[2]
        if k < N
            x = rk4_step(x, step_dt, R, L, C, Vs)
        end
    end

    Vr = R .* i
    Vl = Vs .- Vr .- Vc
    E_inductor = 0.5 .* L .* i.^2
    E_capacitor = 0.5 .* C .* Vc.^2
    E_total = E_inductor .+ E_capacitor

    omega0 = 1.0 / sqrt(L * C)
    alpha = R / (2.0 * L)
    zeta = alpha / omega0

    regime = if zeta < 0.99
        "Underdamped"
    elseif zeta <= 1.01
        "Near Critical Damping"
    else
        "Overdamped"
    end

    return (
        i = i,
        Vc = Vc,
        Vr = Vr,
        Vl = Vl,
        E_inductor = E_inductor,
        E_capacitor = E_capacitor,
        E_total = E_total,
        omega0 = omega0,
        zeta = zeta,
        regime = regime
    )
end

############################
# 2. Interactive Figure & Sliders
############################

fig = Figure(size = (1250, 920), fontsize = 15, figure_padding = 20)

sg = SliderGrid(
    fig[1, 1:2],
    (label = "Resistance R (Ω)", range = 1.0:1.0:150.0, format = "{:.1f} Ω", startvalue = 20.0),
    (label = "Inductance L (mH)", range = 10.0:5.0:500.0, format = "{:.0f} mH", startvalue = 100.0),
    (label = "Capacitance C (μF)", range = 20.0:10.0:500.0, format = "{:.0f} μF", startvalue = 100.0),
    width = 900
)

R_obs = sg.sliders[1].value
L_obs = lift(val -> val * 1e-3, sg.sliders[2].value)
C_obs = lift(val -> val * 1e-6, sg.sliders[3].value)

sim_obs = lift(R_obs, L_obs, C_obs) do R, L, C
    simulate_rlc(t, R, L, C, Vs)
end

header_text = lift(sim_obs, R_obs, sg.sliders[2].value, sg.sliders[3].value) do sim, R, L_mH, C_uF
    "Series RLC Transient ($(sim.regime)) — R=$(round(R, digits=1)) Ω, L=$(round(L_mH, digits=0)) mH, C=$(round(C_uF, digits=0)) μF | ζ=$(round(sim.zeta, digits=3)), ω₀=$(round(sim.omega0, digits=1)) rad/s"
end

Label(fig[0, 1:2], header_text, fontsize = 18, font = :bold)

# Derived reactive observables for plotting
Vc_obs = lift(s -> s.Vc, sim_obs)
i_obs = lift(s -> s.i, sim_obs)
Vr_obs = lift(s -> s.Vr, sim_obs)
Vl_obs = lift(s -> s.Vl, sim_obs)
El_obs = lift(s -> s.E_inductor, sim_obs)
Ec_obs = lift(s -> s.E_capacitor, sim_obs)
Et_obs = lift(s -> s.E_total, sim_obs)

############################
# 3. Four Engineering Plots
############################

# Plot 1: Capacitor Voltage
ax1 = Axis(fig[2, 1], title = "Capacitor Voltage", xlabel = "Time (ms)", ylabel = "Voltage (V)")
lines!(ax1, t_ms, Vc_obs, color = :royalblue, linewidth = 2.5, label = "Vc(t)")
hlines!(ax1, [Vs], color = :gray50, linestyle = :dash, linewidth = 1.5, label = "Step Input ($(Vs) V)")
axislegend(ax1, position = :rb)

# Plot 2: Circuit Current
ax2 = Axis(fig[2, 2], title = "Circuit Current", xlabel = "Time (ms)", ylabel = "Current (A)")
lines!(ax2, t_ms, i_obs, color = :crimson, linewidth = 2.5, label = "i(t)")
hlines!(ax2, [0.0], color = :gray50, linestyle = :dot, linewidth = 1.2)
axislegend(ax2, position = :rt)

# Plot 3: Component Voltages
ax3 = Axis(fig[3, 1], title = "Component Voltages (Vr + Vl + Vc = Vs)", xlabel = "Time (ms)", ylabel = "Voltage (V)")
lines!(ax3, t_ms, Vr_obs, color = :darkorange, linewidth = 2.0, linestyle = :solid, label = "Resistor (Vr)")
lines!(ax3, t_ms, Vl_obs, color = :seagreen, linewidth = 2.0, linestyle = :dash, label = "Inductor (Vl)")
lines!(ax3, t_ms, Vc_obs, color = :royalblue, linewidth = 2.0, linestyle = :dot, label = "Capacitor (Vc)")
axislegend(ax3, position = :rt)

# Plot 4: Stored Energy
ax4 = Axis(fig[3, 2], title = "Stored Energy", xlabel = "Time (ms)", ylabel = "Energy (J)")
lines!(ax4, t_ms, El_obs, color = :seagreen, linewidth = 2.2, label = "Inductor Energy")
lines!(ax4, t_ms, Ec_obs, color = :royalblue, linewidth = 2.2, label = "Capacitor Energy")
lines!(ax4, t_ms, Et_obs, color = :black, linewidth = 1.8, linestyle = :dash, label = "Total Stored Energy")
axislegend(ax4, position = :rt)

# Keep y-limits readable across slider sweeps
on(sim_obs) do sim
    ylims!(ax2, extrema(sim.i) .* 1.15)
    ylims!(ax3, extrema(vcat(sim.Vr, sim.Vl, sim.Vc)) .* 1.15)
    ylims!(ax4, (0.0, max(maximum(sim.E_total) * 1.15, 1e-4)))
end
notify(sim_obs)

colgap!(fig.layout, 24)
rowgap!(fig.layout, 18)

screen = display(fig)
wait(screen)

No comments: