Skip to content

Instantly share code, notes, and snippets.

@rezamarzban
Last active October 23, 2025 04:23
Show Gist options
  • Select an option

  • Save rezamarzban/7361ec66ac228f9af680e7cc98fb68cf to your computer and use it in GitHub Desktop.

Select an option

Save rezamarzban/7361ec66ac228f9af680e7cc98fb68cf to your computer and use it in GitHub Desktop.
* RLC circuit with 50kHz square wave input
V1 1 0 PULSE(0 5 0 10n 10n 10u 20u)
R1 1 2 0.01
L1 2 3 0.1u
C1 3 0 1n
.tran 10n 2000m 1999.8m
.option numdgt=9
.save all
.control
run
set filetype=ascii
wrdata sim.csv v(3)
write sim.raw v(3)
set hcopydevtype=postscript
hardcopy sim.eps v(3)
.endc
.end
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Parameters
R = 0.01
L = 1e-6
C = 1e-7
omega = 2 * np.pi * 50e3
T = 1 / 50e3 # 20 µs period
# State-space function
def rlc(y, t):
i, vc = y
vin = 2.5 + 2.5 * np.sign(np.sin(omega * t)) # Square wave 0-5 V
didt = (vin - R * i - vc) / L
dvcdt = i / C
return [didt, dvcdt]
# Time vector
t_start = 0
t_end = 2000e-3
dt = 10e-9 # 10 ns steps
t = np.arange(t_start, t_end, dt)
# Initial conditions (steady-state approx.)
y0 = [0, 2.5]
# Solve ODE
sol = odeint(rlc, y0, t)
# Extract capacitor voltage
vc = sol[:, 1]
# Select time window 1 ms to 1.2 ms
mask = (t >= 1999.8e-3) & (t <= 2000e-3)
t_plot = t[mask]
vc_plot = vc[mask]
# Plot
plt.figure(figsize=(10, 5))
plt.plot(t_plot * 1e3, vc_plot, color='blue')
plt.title('Capacitor Voltage vc vs Time (1 ms to 1.2 ms)')
plt.xlabel('Time (ms)')
plt.ylabel('Capacitor Voltage vc (V)')
plt.grid(True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment