The following code simulates a resistive 10kΩ
/ 1kΩ
voltage divider using PySpice and can serve as a good starting point for simulating simple circuits.
This post shows you how to simulate the voltage divider using transient analysis. Also see an alternative variant of this post using DC sweep analysis instead: How to DC-sweep resistive voltage divider using PySpice
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('V1', 'in', circuit.gnd, dc_value=5@u_V) # Create resistor divider r1 = circuit.R('R1', 'in', 'n1', 10@u_kΩ) r2 = circuit.R('R2', 'n1', circuit.gnd, 1@u_kΩ) # Simulate for 1 second with steps of 1 millisecond simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.transient(step_time=1@u_ms, end_time=1@u_s)
You can access the array of output voltages of the divider (i.e. node n1
) using analysis['n1']
:
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("Time [ms]") plt.ylim([0.0, 5.5]) plt.gca().yaxis.set_major_formatter(mtick.FuncFormatter(format_volts)) plt.gcf().set_size_inches(8,5) plt.plot(analysis["in"], label="Input voltage") plt.plot(analysis["n1"], label="Voltage divider output") plt.gca().legend() plt.savefig("/ram/PySpice-Voltage-Divider.svg")