shorne in japan

blog about contact

Simulating KiCad Schematics in Spice

28 Apr 2015

KiCad is a great tool for taking your electronics design from schematic to PCB, but circuit simulation is secondary feature.

As we will see here KiCad does contain the ability to generate netlists which can be used with simulators like ngspice to perform circuit verification and analysis.

To get started we will need to decide on a design. I will choose a circuit which will show us how to do following:

  • Use vendor spice components
  • Perform Transient Analysis
  • Simulate an input signal
  • Measure frequency responce

Layout Circuit and Generate Netlist

For this demo let us pick a simple inverting op amp circuit. We can use the spice models from vendors like Texas Instruments and Linear Technology to provide the op amp. This also means we can easily, virtually, swap out components to see how they perform in our design.

Below we can see the completed schematic for a non-inverting op amp with a dual power supply. The 50K ohm feedback and 2K ohm input resistors mean our signal will be amplified 25 times. For more details on drawing schematics in kicad refer to the getting started tutorials.

kicad amp for demo

Image 1: The completed inverting op amp schematic

Once our circuit is complete we can generate a spice netlist by navigating to Tools > Generate Netlist.

Generating a netlist in kicad

Image 2: Generating the spice netlist

Some comments on the Netlist options:

  • The Default format option does not seem to do anything
  • I have selected Prefix references ‘U’ and ‘IC’ with ‘X’, this is needed for ngspice as it recognizes ‘X’ components as subcircuits. However for the Jack and Power interfaces annotated with J* and P* it would be nice to prefix with X as we will implement these with subcircuits as well.

Once the options are selected click Netlist to save your netlist. This will generate a netlist like the following:

* EESchema Netlist Version 1.1 (Spice format) creation date: Sat 25 Apr 2015 07:04:41 AM JST

* To exclude a component from the Spice Netlist add [Spice_Netlist_Enabled] user FIELD set to: N
* To reorder the component spice node sequence add [Spice_Node_Sequence] user FIELD and define sequence: 2,1,0

*Sheet Name:/
XU1  7 6 0 4 1 OPAMP            
J1  2 0 0 JACK_IN              
J2  7 3 0 JACK_OUT             
R2  6 7 50K             
R1  2 6 2K              
R3  0 3 2K              
P1  4 0 1 PWR_IN               


Setup Inputs and Outputs for Simulation

In order to simulate the circuit we need to plug in our virtual power supplies, signal generators and oscilloscope probes. To do this I have chosen to use subcircuits to contain each or these test components.

Create a components.cir like the following:

* Components and subcircuits for use in spicedemo.cir


* 4 0 1 PWR_IN
*              + g -     
.subckt PWR_IN 1 2 3
  Vneg 1 2  3.3V
  Vpos 2 3 3.3V
.ends PWR_IN

* 7 6 0 4 1 OPAMP
*             o - + p n
.subckt OPAMP 1 2 3 4 5
  * PINOUT ORDER  1   3   6  2  4   5
  Xopamp 3 2 4 5 1 NSD LMV981
.ends OPAMP

*               s x g
.subckt JACK_IN 1 2 3
  *** Simulate mic input A-note
  Vmic  3 1 ac SIN(0 0.02 440)
.ends JACK_IN

*                s x g
.subckt JACK_OUT 1 2 3
  Rwire  1 2   10ohm
.ends JACK_OUT

PWR_IN : Connecting Power

This first subcircuit is the PWR_IN connector in our kicad circuit. This is a 3pin connector with a positive rail, negative rail and ground. Here we use two DC power supplies to generate the positive and negative rails. Be sure to double check pin numbers with your generated netlist.


Next we have the OPAMP subcircuit. For this we just provide a wrapper for the component included with .INCLUDE LMV981.MOD. This spice model from Texas Instruments and was selected as it provides a 6 pin low power solution. Many vendors provide models like this which can be used.

TI Spice Model Download

Image 3: Here we can see how to download spice models from Texas Instruments

JACK_IN : Simulating Microphone Input

The JACK_IN and JACK_OUT interfaces are typical mono audo jack interface with 3 pins (called jack 2-pole). The 3 pins are ‘signal’ (tip), ‘ground’ (sleeve) and ‘normally closed (NC)’. When the jack has nothing plugged into it the ‘signal’ and ‘normally closed’ pins will be shorted. When the jack has something plugged in (like a microphone) then the ‘signal’ and ‘ground’ pins will be connected to the microphone and ‘normally closed’ is disconnected. The reason for this is to protect from having floating inputs or outputs or use for jack plug-in detection.

Note: For details on jacks read the wiki and manufacturer documents from Schurter, Adam Tech and Farnell

For JACK_IN we simulate a microphone plugged in by providing a 440hz (a-note) sine wave of 20mV, a typical microphone signal.

JACK_OUT : Simulating a Load

For JACK_OUT we use the dummy load resistor R3 to provide some load to the op amp output. To wire together ‘signal’ and ‘unplugged’ pins we just add a dummy 10ohm resistor. It could have been 0 or 1 ohm, but I just set it to 10.

Update the Generated Netlist

Next, we need to go back and modify the generated netlist slightly to include the components.cir and perform the analysis we wish to do. Also, because we are using subcircuits we add X’s to the J and P components.

Note: Instead of manually adding .include and analysis lines we could add -PSPICE and +PSPICE text blocks anywhere to our kicad schematic and it will include the text before and after the netlist respectively.

.include components.cir

*Sheet Name:/
XU1  7 6 0 4 1 OPAMP
XJ1  2 0 0 JACK_IN
XJ2  7 3 0 JACK_OUT
R2  6 7 50K
R1  2 6 2K
R3  0 3 2K
XP1  4 0 1 PWR_IN


.tran 0.1m 3m
.plot tran V(7) V(2)

.ac dec 10 1 100K
.plot ac V(7)



Running OP Analysis

First its always good to run the dc operating, OP, analsysis to make sure nothing is shorted.

Because we have included the op amp spice model the full analsysis results in more than a thousand lines for dc analysis. The main things to look at our our voltages and currents.

We can check the important voldages with grep as below. Here we can see relatively low voltages other than our supplies which looks normal.

$ ngspice -b spicedemo.cir | grep V\(

        V(3)                             -2.85334e-02
        V(2)                             0.000000e+00
        V(7)                             -2.86760e-02
        V(6)                             -1.13177e-03
        V(1)                             -3.30000e+00
        V(4)                             3.300000e+00

To view the currents we can run a similar grep and see similar low values (less than 1 milliamp). Its good to look at the entire output to understand how these greps work.

$ ngspice -b spicedemo.cir | grep v\\.x

        v.xj1.vmic#branch                5.658851e-07
        v.xp1.vneg#branch                -1.37178e-04
        v.xp1.vpos#branch                -1.51996e-04

Running TRAN Analysis.

Next we can run the TRAN analsysis (oscilloscope mode), to make sure it works. Here we can see that the input signal is amplified from 20mV to 500mV resulting in our expected 25 times gain. The result is also inverted as we are using an inverting amp configuration.

# In interactive mode
$ ngspice spicedemo.cir

> tran 0.3m 1m
> plot V(2) V(7)

TRAN analysis results

Image 4: Transient analysis, shows the input signal in blue and output in red

Running AC Analysis

Finally running AC analysis we can measure the frequency responce (bandwidth) of the circuit. Below we can see that after about 10,000 Hz the gain starts to drop off.

# In interactive mode
$ ngspice spicedemo.cir

> ac dec 10 1 100K
No. of Data Rows : 51
> plot V(2) V(7)

Ac analysis results

Image 5: Shows performance drop off after 10K hz

Further Reading

Spice Essentials

21 Apr 2015

Did you ever get stuck figuring out how to run spice? These essential spice tips will get you on your way.

Recently I have been searching for good linux tools to simulate circuits. Spice is widely known in circuit simulation. This short guide should help you get started; including how to perform graphical plotting with nutmeg. All the below demos are using ngspice and ngnutmeg. In this post I assume you know the basics of writing or generating spice netlists.

We will cover the basics of:

  • Analysis with OP and TRAN
  • Controlling spice output
  • Running ngspice and ngnutmeg


When analyzing a circuit we need to use spice analysis commands. These are usually placed at the end of your netlist.

Using OP

The first and most simple analysis command you should know is the OP command. It provides the dc operating point voltage dump of all nodes with capacitors fully charged (no current) and inductors fully inducting (shorted).




Download op.cir

* OP analysis of Voltage divider 
V1 2 0 DC 10V
R1  2 1 50K             
R2  1 0 20K             

When running we can see that the voltage and current of each node is displayed.

$ ngspice -b op.cir

No. of Data Rows : 1
        Node                                  Voltage
        ----                                  -------
        ----    -------
        V(1)                             2.857143e+00
        V(2)                             1.000000e+01

        Source  Current
        ------  -------

        v1#branch                        -1.42857e-04

Using TRAN

The next analysis command to know is the TRAN command.

TRAN will run the circuit for a fixed time and take interval measurements. The below .tran 0.1m 5m will measure for 5 milliseconds and output every 0.1 milliseconds. It should print 50 readings. You should choose your measurements based on the frequency of the input source to allow you to see the full wave,



  • STEP - is the time interval of how often a measurement is taken
  • END - is the time when spice will end measurement
  • START - (default 0) is the time when spice will start measurement
  • MAX - is used to define a STEP smaller than STEP (yeah confusing)

Note: spice manuals mention the step time of TRAN is not always used by spice. If END-START/50 is less than STEP spice will set step to the smaller value. I haven’t seen this affect my simulations yet.


Download tran.cir

* TRAN analysis of RC circuit
Vin  2 0 AC SIN(0 0.02 440)
R5  2 1 1K
C1  1 0 4.7uF
.tran 0.1m 3m
.plot tran v(2), v(1)

When running we can see a plot printed of our analysis.

$ ngspice -b tran.cir

No. of Data Rows : 63
                       * ac analysis of rc circuit
               Transient Analysis Tue Apr 21 22:55:08  2015

Legend:  + = v(2)             * = v(1)             
 time       v(2)    -2.00e-02   -1.00e-02    0.00e+00    1.00e-02    2.00e-02   
 0.000e+00  0.000e+00 .           .           X           .           .   
 1.000e-04  5.456e-03 .           .           *     +     .           .   
 2.000e-04  1.047e-02 .           .           *           +           .   
 3.000e-04  1.471e-02 .           .           *           .    +      .   
 4.000e-04  1.786e-02 .           .           *           .        +  .   
 5.000e-04  1.958e-02 .           .           .*          .          +.   
 6.000e-04  1.987e-02 .           .           .*          .          +.   
 7.000e-04  1.867e-02 .           .           . *         .         + .   
 8.000e-04  1.598e-02 .           .           . *         .      +    .   
 9.000e-04  1.213e-02 .           .           .  *        . +         .   
 1.000e-03  7.356e-03 .           .           .  *    +   .           .   
 1.100e-03  2.000e-03 .           .           . +*        .           .   
 1.200e-03 -3.490e-03 .           .      +    .  *        .           .   
 1.300e-03 -8.736e-03 .           .+          . *         .           .   
 1.400e-03 -1.328e-02 .       +   .           . *         .           .   
 1.500e-03 -1.684e-02 .  +        .           . *         .           .   
 1.600e-03 -1.916e-02 .+          .           .*          .           .   
 1.700e-03 -1.993e-02 +           .           .*          .           .   
 1.800e-03 -1.926e-02 +           .           *           .           .   
 1.900e-03 -1.714e-02 .  +        .           *           .           .   
 2.000e-03 -1.365e-02 .      +    .          *.           .           .   
 2.100e-03 -9.168e-03 .           +          *.           .           .   
 2.200e-03 -3.990e-03 .           .      +   *.           .           .   
 2.300e-03  1.502e-03 .           .          *.+          .           .   
 2.400e-03  6.873e-03 .           .          *.       +   .           .   
 2.500e-03  1.175e-02 .           .          *.           . +         .   
 2.600e-03  1.567e-02 .           .           *           .     +     .   
 2.700e-03  1.845e-02 .           .           *           .         + .   
 2.800e-03  1.986e-02 .           .           *           .          +.   
 2.900e-03  1.967e-02 .           .           .*          .          +.   
 3.000e-03  1.810e-02 .           .           .*          .        +  .   
 time       v(2)    -2.00e-02   -1.00e-02    0.00e+00    1.00e-02    2.00e-02   

elapsed time since last call: 0.018 seconds.

Controlling Output

To output data during simulation we use the PLOT and PRINT commands. These commands work together with dynamic analysis commands like TRAN to output analysis data points.

The plot command will plot a ascii chart of analysis.

.plot tran v(1), v(8)

The print command will print the value of the analysis.

.print tran v(1), v(8)

Running Spice

When simulating a circuit we have a few options.

# Running in batch mode
$ ngspice -b op.cir
# Running in interactive move
$ ngspice
> source op.cir
> run
# will display output as above
> edit
# Will allow editing of your circuit

Another option is to output the analysis data in raw format. This data can then be loaded up in ngnutmeg for further analysis.

# This commands runs the analysis in preamp.cir and outputs raw data to
# tran.raw
ngspice -b tran.cir -r tran.raw
# The below command loads the raw file into ngnutmeg and then displays the
# ngnutmeg prompt. The `plot v(1)` command will bring up a view of the wave form
ngnutmeg tran.raw
> plot v(2) v(1)

NGNutmeg Analysis

Further Reading

Keep an eye on this stack exchange discussion which mentions other tools for simulating circuits in linux.

These guides have been very help:

Compiling Verilog on the Command Line with ModelSim

05 Apr 2015

Lately I have been working on some projects using verilog. My main development environment has been Altera Quartus II which works fine. However, when compiling in quartus we don’t always need to go through all of the sythesis and timing steps, instead one may just need to verify their source code is compilable.

The vlog compiler included with ModelSim can be used to quickly compile your HDL.

 # Add module sim onto your path
 $ PATH=$PATH:/usr/share/altera/14.0/modelsim_ase/bin

 # Create a library directory used by 'vlog', by default it looks for 
 # the 'work' library
 $ vlib work

 # Perform the verilog compile
 $ vlog dram_controller.v

 Model Technology ModelSim ALTERA vlog 10.1e Compiler 2013.06 Jun 12 2013
 -- Compiling module dram_controller

 Top level modules:

You can find more details on using ModelSim’s command line utilties at the ncsu modelsim tutorial.

Setting up USB-Blaster in Linux

30 Jul 2014

Today I got my DE0-Nano FPGA development board. The first thing I wanted to do was get the linux connectivity setup; so I plugged it in. The device was recognized as character devide by linux right away.

Next, I checked Altera to see if anything special was needed for getting USB-Blaster setup in linux. They recommend some udev example rules to make the device file world writable, I guess that is ok. I dropped the udev rules into /etc/udev/rules.d/51-usbblaster.rules and unplugged then replugged the device but nothing happened.

I havent setup udev rules for a while, so right away I wasn’t able to spot the problem. I was able to test the rules using udevadm as below.

    udevadm test /bus/usb/devices/3-1

It complained that BUS and SYSFS matchers were not valid. They were removed in 2011 according to the udev changelog.

Using udevadm we are also able to see the proper attributes that we should be matching. Below is what I have come up with to properly setup USB-Blaster in linux. I am using Fedora 18.

    udevadm info -a --path=/sys/bus/usb/devices/3-1

My USB-Blaster udev Rules

    # USB-Blaster
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6001", MODE="0666", SYMLINK="usbblaster%n"
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6002", MODE="0666"
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6003", MODE="0666"
    # # USB-Blaster II
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6010", MODE="0666"
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6810", MODE="0666"

Note, since my device is a 6001 I setup a symlink which will make it easily accessable at /dev/usbblaster1.

Hopefully this will be helpful to other people.

Move to github pages

10 Jul 2014

This is my first post to my new blog using Jekyll.

Lets see how it goes, I want to:

  • Notes on technology I am using (Verilog, Javascript, Rails, C)
  • Links to code
  • Blogs
  • Maybe import my old blog here