Processing math: 100%

Thursday, January 16, 2014

RLC circuit tuner

I got bored of calculating resonances by hand, so here's a tuner for an RLC circuit. The transfer function is the ratio of the voltage across R_L to the input voltage.

 

 RLC circuit tuner

import matplotlib as mpl
#mpl.rc('text', usetex = True)
#mpl.rc('font',**{'family':'serif','size':16,'weight':'bold','serif':['Palatino']})
from __future__ import division
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
def ser(A,B): return A+B
def par(A,B): return A*B/(A+B)
def H(f,L,C,R,RL):
# Resonant circuit
omega = 2*pi*f
X_L = 1j*omega*L
X_C = 1/(1j*omega*C)
Z0 = par(par(X_L,X_C),RL)
return Z0/(R+Z0)
# Random initial values
L = 1e-3 # H
C = 1e-3 # F
R = 1e1 # Ohms
RL = 1e3 # Ohms
f = np.arange(0.1,1000,0.1)
fig = plt.figure(figsize=(9,4.5))
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
lmag, = ax1.plot(f,np.abs(H(f,L,C,R,RL)))
lphase, = ax2.plot(f,np.angle(H(f,L,C,R,RL)),'g')
ax2.grid(which='major',axis='y')
ax2.set_ylabel("Phase[H(f)] [rad]",color='g')
ax1.set_ylabel("Magnitude, |H(f)|",color='b')
ax1.set_xlabel("Frequency, f [Hz]")
#plt.tight_layout()
fig.subplots_adjust(bottom=0.11*4)
#plt.subplots_adjust(left=0.10)
#plt.subplots_adjust(right=1.00)
ax = []
slider = []
axcolor = 'lightgoldenrodyellow'
class Parameter:
def __init__(self,label,limit,value):
self.label = label
self.limit = limit
self.value = value
params = [ Parameter('log10 L',[-6,-1],-3), \
Parameter('log10 C',[-9,-2],-4), \
Parameter('log10 R',[0,8],2), \
Parameter('log10 RL',[0,9],6)]
for i in range(len(params)):
ax.append( plt.axes([0.25, 0.26-0.05*i, 0.65, 0.03], axisbg=axcolor) )
slider.append( Slider(ax[i],params[i].label,params[i].limit[0],params[i].limit[1],valinit=params[i].value) )
def update(val):
L = 10**slider[0].val
C = 10**slider[1].val
R = 10**slider[2].val
RL = 10**slider[3].val
lmag.set_ydata( np.abs(H(f,L,C,R,RL)) )
lphase.set_ydata( np.angle(H(f,L,C,R,RL)) )
fig.canvas.draw_idle()
for i in range(len(params)): slider[i].on_changed(update)
update(0)
view raw RLCtuner.py hosted with ❤ by GitHub