The following code simulates a resistive 10kΩ
/ 1kΩ
voltage divider using PySpice using a DC sweep and can serve as a suitable starting point for simulating simple circuits. We sweep from 0V
to 5V
in steps of 10mV
.
Also see our previous post How to simulate resistive voltage divider using PySpice for an alternate version using transient analysis:
import PySpice.Logging.Logging as Logging logger = Logging.setup_logging() from PySpice.Probe.Plot import plot from PySpice.Spice.Netlist import Circuit from PySpice.Unit import * circuit = Circuit("MyCircuit") # Create voltage source: 5V DC source = circuit.VoltageSource('in', 'in', circuit.gnd, [email protected]_V) # Create resistor divider r1 = circuit.R('R1', 'in', 'n1', [email protected]_kΩ) r2 = circuit.R('R2', 'n1', circuit.gnd, [email protected]_kΩ) # Simulate for 1 second with steps of 1 millisecond simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.dc(Vin=slice(0, 5.0, 0.01))
You can access the array of output voltages of the divider (i.e. node n1
) using analysis['n1']
. Keep in mind that if the first argument of circuit.VoltageSource
is 'in'
, the argument to simulator.dc
will be valled Vin
, not just in
! A V
will automatically be prepended!
This is the code we used to plot this:
import matplotlib.ticker as mtick import matplotlib.pyplot as plt from UliEngineering.EngineerIO import format_value def format_volts(value, pos=None): return format_value(value, 'V') plt.style.use("ggplot") plt.xlabel("Input voltage") plt.xlabel("Divider output voltage") plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(format_volts)) plt.gca().xaxis.set_major_formatter(mtick.FuncFormatter(format_volts)) plt.gcf().set_size_inches(8,5) plt.plot(analysis["in"], analysis["n1"], label="Input voltage") plt.savefig("/ram/PySpice-Voltage-Divider-Sweep.svg")