The EasyEDA Simulation eBook

Written for EasyEDA 

by Andy Fierman

signality.co.uk

This version: 180409

Editing in progress to correct typos, improve text and create tables in Markdown

Edited from original document:

ebook_02_w_ToC_151021.html

(to which was added a title page and Table of Contents heading.)

In lines beginning with one or more # characters, the # can be ignored.

Where text is enclosed in 1, 2 or 3 asterisks such as:

*text*

**text**

***text***

the asterisks can be ignored.

Where text is enclosed in backticks (`) such as:

`text`

the backticks can be ignored.


Table of Contents

# Introduction        5

## What this book is for        5

## What this book is *not* for        5

## Who this book is for        6

## How the book is structured        7

# Introductory concepts of simulation        9

# About naming conventions        10

# Introduction to using a simulator        11

## Avoiding common mistakes        12

### Prefix conflict error        12

### All simulation circuits MUST have a ground node        13

### The ground node MUST NOT have a Voltage Probe attached to it.        13

### All simulation circuits MUST have a power and/or signal source        13

### Every point in a simulation schematic MUST have a DC path to ground        14

#### Values and DC paths of RLC components        14

#### DC paths through Voltage and Current Sources        16

#### The effects of adding DC paths        17

#### Common problems with DC paths        20

### Components are connected by netnames        21

# Probing signals        22

## Probing voltages        23

## Probing currents        24

# Advanced probing and simulation control        25

## The `probe` command        25

### What the `probe` spice directive does        25

### The syntax of a `probe` directive        26

### Using the 'probe' command to make measurements        27

### Probing instantaneous power        28

### Probing resistances and conductances        28

## Using CTRL+R to run a simulation directly        28

## The `let` command        29

# Configuring Voltage and Current Sources        30

## Configuring the SIN or SINE option        31

## More ways to use the SIN (or SINE) option        31

## Configuring the PULSE option        31

## More ways to use the PULSE option        31

## Configuring the EXP option        31

## Configuring the SFFM option        31

## Configuring the AM option        32

## Configuring the PWL option        32

## Configuring the AC source option        32

# Setting up Analyses        33

## What are Analyses?        33

### SPICE Analyses available from the Super Menu> Miscellaneous > Simulate menu        34

### SPICE Analyses and Control Statement Syntax        34

#### 1) OP: Perform an Operating Point Analysis        35

#### 2) TF: Perform a DC Transfer Function Analysis        35

#### 3) DC: Perform a DC-Sweep Analysis        36

#### 4) AC: Perform a Small-Signal AC (frequency domain) Analysis        37

#### 5) TRAN: Perform a Transient (time domain) Analysis        37

#### IC: Set Initial Conditions        38

# Initial conditions and starting up circuits        40

## Some background and basic start-up techniques        40

## Setting initial voltages on nets and currents through components        43

### Using the `.ic` spice directive to set an initial voltage condition on a net        43

### Using a current source to set an initial current through an inductor        44

### Setting a capacitor voltage using an XSPICE capacitor model        44

### Setting an inductor current using an XSPICE inductor model        44

## Using a 1V source to help start-up        44

## Replacing ideal and Thevenin voltage sources with band-limited Norton Sources to help start-up        45

## Using the 'OFF' option to help start-up        46

# Expressions        47

## Operators        47

## Using Expressions to define component values        49

## Using Expressions to configure voltage and current sources        50

# Parameters        51

## Using parameters in expressions        54

# Functions        54

## Predefined functions        54

**Table of functions**        54

## User defined functions        57

# B sources        58

# Device models        60

## Why are there different models for the same device?        61

## .model statements        62

### Ngspice model types        62

## .subckt definitions        63

## Behavioural models        63

## What if there is no model available for a device?        63

## The relationship between spice models and device datasheets        64

## The relationship between spice models and real world behaviour        66

## How to change the model attached to a symbol        68

### For .MODEL defined models        69

### For .SUBCKT defined models        70

### Attaching models to custom symbols        73

# Schematic symbols: prefixes and pin numbers        73

## PCB and Spice Prefix        74

## PCB and Spice pin numbers        77

# Custom modelling        81

# Making measurements of simulation results        81

## Using the WaveForm display cursors        82

## Using the meas command        82

## The meaning of terms in MEAS commands        82

## Examples of the forms and syntaxes of MEAS commands        83

### Trig Targ        83

### Find ... When        84

### AVG | MIN | MAX | PP | RMS | MIN_AT | MAX_AT        86

### INTEG        87

### DERIV        87

### More examples of measure statements        88

# Introduction

EasyEDA is not just a way to draw circuit diagrams and design PCBs. It is also a circuit simulator.

A circuit simulator is basically a specialised mathematical program, optimised to construct and then solve the equations that define the behaviour of the circuit that has been described to it in the circuit diagram.

The circuit simulation program that EasyEDA uses is called ngspice. Ngspice is Free and Open Source Software (FOSS) that is in turn based on a simulator called SPICE that was originally written by Larry Nagel.

## What this book is for

This book is an introduction to circuit simulation in EasyEDA using ngspice.

It starts with the basics of how to avoid some of the most common mistakes that cause simulations to fail and then goes on to illustrate how to set up a circuit so that it will simulate successfully and produce meaningful results. It also discusses some aspects of understanding how, what might at first appear to be unexpected or even nonsensical results, can arise.

The book then introduces and illustrates more advanced techniques such as:

* probing signals such as voltages, currents, powers and resistances;

* configuring signal sources;

* setting up different types of analyses;

* making measurements such as rise times, RMS values and bandwidths;

* defining component values using parameters;

* using expressions to calculate component values such as for a resistor to draw a given load current or capacitances for a specified filter cutoff frequency;

* using manufacturer's device models;

* setting up complex simulations including arbitrary voltage and current sources.

## What this book is *not* for

* This is not a book about learning to use EasyEDA to draw schematics. For general information about using EasyEDA please refer to the >[EasyEDA Tutorial](https://docs.easyeda.com/en/Introduction/Introduction-to-EasyEDA/index.html).

* This book does not teach electronics. Whilst there may be examples of circuits and explanatory text that are helpful in understanding electronics, it is assumed that the user already has sufficient knowledge of electronics to understand the content of this book.

* Although ngspice is similar to other variants of spice and a lot of the information and techniques in this book may be applicable to some of those variants, this book is written specifically about circuit simulation in EasyEDA using ngspice.

* Except where necessary to help explain some aspect of the behaviour of simulation, this book does not go into any detail of how circuit simulation in general and ngspice in particular actually works. For more information about those areas, please see the links below:

More information about Larry Nagel and SPICE is available from here:

http://www.omega-enterprises.net/The%20Origins%20of%20SPICE.html

Larry Nagel's PhD Dissertation:

>*Laurence W. Nagel., “SPICE2: A Computer Program to Simulate Semiconductor Circuits,”

Memorandum No. ERL-M520, University of California, Berkeley, May 1975.*

http://www.eecs.berkeley.edu/Pubs/TechRpts/1975/ERL-520.pdf

is actually very readable and instructive.

For more information about electronic circuit simulation and spice in particular, see:

http://en.wikipedia.org/wiki/Electronic_circuit_simulation 

and:

http://en.wikipedia.org/wiki/SPICE 

More information about ngpsice is available from here:

http://ngspice.sourceforge.net/presentation.html

## Who this book is for

All simulation tools and how they interact with schematic capture tools are different so even for people with experience of using simulation tools, it is worth at least skimming through the sections of this book to get an idea of where to find information if things don't seem to go quite as expected.

However, for people with limited or no previous experience of using simulation tools, this book is *essential* reading.

Why?

Because, as a newcomer to the world of circuit simulation, it is very tempting just to launch straight into trying to build and run lots of interesting and exciting simulations.

Sadly, however, this will almost certainly be a very frustrating and discouraging experience because many of those simulations will either not run, will not function correctly as circuits or will appear to give nonsensical results! This can happen for all sorts of often very simple reasons but to newcomers with no experience of simulation, those reasons can seem utterly incomprehensible.

So, to avoid a lot of discouragement and wasted time, it is worth taking a few minutes to understand some of the most common things that can cause a simulation to fail or to run but give unexpected answers.

## How the book is structured

This book is not some dry tome with lots of words, diagrams and snippets of code. It is written as a live, interactive document. Rather than having to read lots of text and then having to go into EasyEDA to create circuits to try things out, live simulation examples are embedded directly into the text to illustrate the points being discussed.

Just go to a topic or a section heading; read a couple of paragraphs and then open and run the embedded simulation to see exactly what the text is about.

Every embedded simulation must be saved before it can be run. Users who have joined EasyEDA can save the files to their own project folder. The examples can be copied and edited so that users can try out different things in whatever way helps their understanding of what the example is trying to explain, building up their own personal library of teaching examples as they progress through the book.

Newcomers are encouraged to work through the book in a linear manner because each section builds on the knowledge and insights gained from all the previous ones. Skipping sections leaves gaps that can catch out the novice and hinder the understanding of ideas presented in later sections.

* The book begins by introducing some of the concepts and terms that are essential for a basic understanding of what a simulator is and how to use it effectively.

* Then, using simple interactive simulation examples it describes and illustrates how to avoid the most common pitfalls in building, running and interpreting the results from simulations.

* The book goes on to illustrate ways to create and show connectivity using wires and netlabels in schematics. It then discusses techniques for probing voltages and currents and how they relate to and can affect or be affected by the netnames that are assigned to nets either automatically by EasyEDA or manually by the user placing netlabels.

* More advanced techniques for probing voltages and currents using the `probe` command are described, moving on to using this command to measure power dissipations, resistances and conductances.


This section describes the use of 0V sources to measure currents also introduces and E, F, G and H dependent sources and the very powerful arbitrary or B Dependent Sources.
In this section, the concept of the `Spice Directive` is also introduced, describing how to turn inactive `comment` text into active `spice` text that the simulator then recognises as an instruction to do something.

* The `probe` concept is then extended by describing how several different 'probe' commands can be typed into a schematic and - simply by selecting which one is switched from being 'comment' text into 'spice' text - they can be used to swap between different selections of values and nodes to be probed.

* The use of the `let` command to further extend and simplify the probing of signals is introduced with a simple example. This command will feature heavily in later sections about making measurements based on the results of simulations.

* Early interactive simulation examples introduce the basic way of setting up and running a simulation using the **Tools > Simulation > Simulate this Sheet** option to open the `Run your simulation` dialogue and then select the type of analysis to run.

* Later examples show how to use the **CTRL+R** Hotkey as a shortcut to the `Run your simulation` dialogue.


This idea is then extended with the concept of using `spice directives` to run simulations straight from the **CTRL+R** Hotkey so that, with a few simple key strokes, it is easy to switch between several different simulations from a single simulation schematic.

* DC operating point, DC Transfer function, DC Sweep, AC (frequency domain) and Transient (time domain) Analyses are described in some detail.


Using the DC Sweep to sweep the value of a resistance in a circuit and to sweep the ambient temperature for circuit is covered in this section.


There are detailed sections on setting up each of the various time domain signal sources that are available, such as SINE, PULSE and more.

Configuring and using the frequency domain AC source that is built into to every independent signal source is covered.

* The need for and different ways of defining initial conditions such as voltages on nets and across capacitors and currents in inductors are demonstrated.


Using PULSE, EXP, PWL and B Sources to 'kick start' circuits is also illustrated in this section.

* The concept of using parameters (i.e. variables that are used in the simulation) to define things like multiple component values and signal source settings is described.

* The use of parameters in expressions (i.e. formulas or equations) to calculate values such as the capacitance for a given RC time constant with a given resistance is covered and then extended into using them in B Sources.

* The concept of predefined functions and their use in expressions is described in detail extending into the creation of user defined functions using the `.func` statement.

* The concept and scope of device models in simulation is discussed in detail.

* Ways to add 3rd party models and subcircuits into schematics and to use them with the predefined schematic symbols from the EasyEDA Libs is covered in detail.

* The use of 3rd party models is extended into attaching them to custom schematic symbols.

* The use of expressions and functions in the creation of custom behavioural models is covered with reference to some of the in-house EasyEDA (EE suffix) models.

# Introductory concepts of simulation

For every circuit being simulated, EasyEDA converts the schematic into a textual description of the circuit that is then passed to the simulator.

This textual description of the circuit is called a **spice netlist**.

* Note that the spice netlist is not the same as the netlist that is generated from a schematic and which is then passed through to PCB layout.

The netlist is a list of all the components used, how they are connected together and descriptions of them, called **models**, so that the simulator knows the behaviour of each component is to be simulated. The netlist also includes instructions to the simulator, called **spice directives**, to tell it what type of **analysis** is to be run. It may also include lists of values, called **parameters**, that are to be used to directly define component values or as part of more extensive calculations, called **expressions**.

Just like real ones, circuits to simulated require power sources and often signal sources. Therefore the netlist will include any **voltage sources** and **current sources**. These can be **Independent Sources** or **Dependent Sources**. Independent Sources just generate DC voltages or currents or can generate time domain signals such as sinusoids and pulses or they can generate a signal of a given amplitude and phase for frequency domain simulations (in fact they can be configured to generate all three but that will be covered later). Dependent Sources can also be used to generate DC voltages or currents but their main use is to generate outputs that are **functions** of that other signals in the circuit, for example by using an expression to describe the output of a source as a current that is equal to the sum of the squares of two input voltages.

The netlists of more advanced simulations can include instructions, called **measure statements**, to the simulator to perform calculations on the results of the simulation itself, for example to measure the rise time of a pulse, the RMS value of a signal or the 3dB bandwidth of a filter circuit.

# About naming conventions

Before going any further it is important to understand the naming conventions used throughout this book and throughout all the simulations.

Unless stated otherwise, text in Spice simulations is case insensitive.

Permissible characters are: `a` to `z`, numbers `0` to `9` and the underscore character: `_`.

Fields on a line are separated by one or more blanks, a comma, an equal (=) sign, or a left or right parenthesis; extra spaces are ignored.

A line may be continued by entering a `+` (plus) in column 1 of the following line; ngspice continues reading beginning with column 2.

A name field must begin with a letter (A through Z) and cannot contain any delimiters.

A number field may be an integer field (12, -44), a floating point field (3.14159), either an integer or floating point number followed by an integer exponent (1e-14, 2.65e3), or either an integer or a floating point number followed by one of the following scale factors:

**Suffix**

**Name**

**Factor**

T

Tera

1e12

G

Giga

1e9

**Meg**

**Mega**

**1e6**

K

Kilo

1e3

mil

Mil

25.4×1e-6

**m**

**milli**

**1e-3**

u

micro

1e-6

n

nano

1e-9

p

pico

1e-12

f

femto

1e-15

Markdown version of table:

|Suffix        |Name                |Factor        |

|---                 |---                |---                |

|T                |Tera                |1e12                |

|G                |Giga                |1e9                |

|**Meg**        |**Mega**        |**1e6**        |

|K                |Kilo                |1e3                |

|mil                |Mil                |25.4×1e-6        |

|**m**        |**milli**        |**1e-3**        |

|u                |micro        |1e-6                |

|n                |nano                |1e-9                |

|p                |pico                |1e-12        |

|f                |femto        |1e-15        |

Letters immediately following a number that are not scale factors are ignored and letters immediately following a scale factor are ignored. Hence, 10, 10V, 10Volts, and 10Hz all represent the same number, and M, MA, MSec, and MMhos all represent the same scale factor. Note that 1000, 1000.0, 1000Hz, 1e3, 1.0e3, 1kHz, and 1k all represent the same number.

* Note that `M` or` m` denote `'milli`, i.e. 1e-3

* The suffix `Meg` MUST to be used for 1e6

Node names may either be plain numbers or arbitrary character strings, not starting with a number.

The ground node must be named `0` (zero). For compatibility reasons `gnd` is accepted as the ground node and will internally be treated as a global node and be converted to `0`.

Note the difference in ngspice where the nodes are treated as character strings and not evaluated as numbers, thus `0` and `00` are distinct nodes in ngspice (whereas they are not in SPICE2).

Ngspice and therefore, EasyEDA, requires that the following topological constraints are satisfied:

* Each circuit has to have a ground node (`gnd` or `0`)!

* The circuit cannot contain a loop of voltage sources and/or inductors and cannot contain a cut-set (series connected set) of current sources and/or capacitors.

* Each node in the circuit must have a dc path to ground.

* Every node must have at least two connections except for transmission line nodes (to permit unterminated transmission lines) and MOSFET substrate nodes (which have two internal connections anyway).

These constraints will be covered in more detail later,

# Introduction to using a simulator

Using a simulator is not quite the same as building a real circuit. There are many things that can catch out the newcomer to simulation because neither real world nor most simulator components are ideal. The departures from ideal are often different between the two and if these differences between real and simulated components in a circuit are not clearly understood, they can lead to confusion when the results of a even a simple simulation are different from those expected.

Part of the problem is that a user's expectations are informed by experience of real world measurements. Therefore, it is important to understand exactly what measurements are being made and how the simulation circuit will affect the results. In cases where there are differences between real and simulated results this may also require a deeper understanding of what is going on in those circuits and what assumptions are being made - often unconsciously - about them.

Learning to use a simulator means thinking more about what the real world *really* looks like, how it differs from the theoretical world of textbook problems and simple diagrammatic circuit representations and therefore what the results of measurements are likely to be.

## Avoiding common mistakes

The following section describes and illustrates some of the most common mistakes, misunderstandings and causes for confusion.

### Duplicate Components Prefix error

This error message will appear:

If:

>There are two copies of the same schematic in the same project folder: CctA and Copy_of_CctA.

>In this case, the component prefixes (reference designators) will be the same in both CctA and Copy_of_CctA.

> Or:

>There are two different schematics in the same project folder, CctA and CctB but there are some components in CctB that have the same prefixes as in CctA.

Then:

>If a simulation run is attempted using:

>>**Tools > Simulation > Simulate complete Schematic**

>then EasyEDA will try to merge all the schematics in the Project into a single schematic and then run a simulation on that big schematic.

This will fail because EasyEDA will find repeated instances of components with the same prefix.

Else:

>if you try to run a simulation using:

>>**Tools > Simulation > Simulate this Sheet**

>or:

>>**CTRL+R**

>then EasyEDA will run a simulation only on the schematic in the current active tab in the editor window (if you have only one schematic open then it will run that one but if you have more than one schematic open then it will run only the one in the selected tab).

If you have given a unique prefix to every component in that selected sheet then this simulation will run because EasyEDA will find only single instances of every component in the schematic.

### All simulation circuits MUST have a ground node

A feature of the way simulators work is that they MUST have a ground node (also referred to as the 0 net) somewhere in the circuit. All voltages probed in the circuit, unless explicitly probed as voltage differences are then measured with respect to that ground node. The ground node can be placed anywhere in the circuit that is convenient for the purposes of the simulation but it must exist somewhere in that circuit.

>***SIMULATION SCHEMATICS THAT DO NOT HAVE A GROUND NODE WILL NOT RUN.***

This is illustrated in the following two examples:

With no ground symbol, the simulation will not run:

>[All simulation schematics MUST have a ground 01](https://easyeda.com/editor#id=235fccd4a9984b0e9a49a42d81854435)

Once any of the available ground symbols is added, the simulation will run:

>[All simulation schematics MUST have a ground 02](https://easyeda.com/editor#id=2b49249c3bc44539896225ee1db7fdb4)

### The ground node MUST NOT have a Voltage Probe attached to it.

The reason for this is explained later in the section on **Probing Voltages**.

### All simulation circuits MUST have a power and/or signal source

In exactly the same way that a real circuit must have some sort of power supply - even if that power supply is actually the signal source itself (for example, a crystal set or a volume control potentiometer) or comes from a capacitor pre-charged to some voltage or an inductor pre-charged to some current prior switching the circuit on - a simulation schematic must have a power and/or a signal source or an initial condition such as a capacitor pre-charged to some voltage or an inductor pre-charged to some current prior to the start of the simulation.

Power supplies can be built from ideal zero series resistance voltage sources. Simple but more realistic models of battery and voltage regulator supplies can be built using voltage sources with some series resistance or current sources with a parallel resistance (i.e. Thevenin or Norton equivalent sources).

EasyEDA provides a wide range of signal sources. These will be covered in detail in their own section on Sources but the basic use of some of these sources to provide power to a circuit is illustrated below:

>[All simulation schematics MUST have a power supply too](https://easyeda.com/editor#id=33ceeaef756d4e4d81aef87c9b9f25ea)

### Every point in a simulation schematic MUST have a DC path to ground

Unlike real circuits, every point in a simulation schematic MUST have a DC path to ground (or 0 net). Attempting to run a simulation with a node that has no DC path to ground will fail with errors.

Before discussing the significance of the DC path to ground, however, it is essential to look at some of the basic components and sources that are used in almost all simulations and to understand how they affect these DC paths.

#### Values and DC paths of RLC components

This section is about the values of - and DC paths through - resistors, inductors and capacitors.

* Inductors in ngspice have zero series resistance (i.e. ESR = 0).

 >* Therefore, inductors have a DC path through them.

* Inductors in ngspice have no parasitic parallel capacitance or resistance.

* Capacitors in ngspice have no parasitic parallel conductance (i.e. they have an infinite DC resistance).

 >* Therefore capacitors in ngspice do not have a DC path.

* Capacitors in ngspice have zero series resistance (i.e. ESR = 0).Capacitors in ngspice have no parasitic series inductance (i.e. ESL = 0).

* Inductors and capacitors in ngspice can be set to positive and to negative values and to zero. Beware that setting a component to a negative value may cause the circuit connected to them to exhibit instability or oscillation. This in turn may cause the simulation to fail.

* Resistors obviously have a DC path through them.


Resistors in ngspice can be set to positive and to negative values but cannot be set to exactly zero: they MUST have a non-zero value. Setting a resistance to zero will cause the simulation run to fail with an error. This is basically because any voltage difference across a zero resistance (such as may occur normally in a circuit or even just as a consequence of numerical "noise" in the simulation calculations) will generate an infinite current, which will obviously crash out of the top end of the simulators calculation dynamic range. This applies to all resistors in ngspice, including the Ron and Roff values in switches and resistances given in device models.
Beware that setting a resistor to a negative value may cause the circuit connected to it to exhibit instability or oscillation. This in turn may cause the simulation to fail.

* A common cause of confusion in simulation is the apparently unexpected behaviour of circuits using open circuit switches.


Just like switches in the real world, switches in EasyEDA have non-zero ON resistances (Ron). They also have finite OFF resistances (Roff). If an EasyEDA switch is connected in series with a voltage source into an open circuit load (such as presented by a Voltage Probe) then the voltage at the output of the switch will be equal to the open circuit voltage of the voltage source *whether the switch is open or closed*. This is different from the real world experience because in a real circuit, the voltage would be measured with a voltmeter or an oscilloscope probe having a much lower resistance than the open circuit resistance of the switch.


To illustrate this, let’s take a simple example of a switch connected in series with an ideal voltage source set to 1V and then measure the V(Output) of the switch when open and closed.


With the switch closed the expected output is V(Output) = 1V.


And that’s what the simulation shows.


OK. With the switch open the expected output is V(Output) = 0V.


What the simulation actually shows is V(Output) = 1V.


What’s that all about? Surely the switch must not be simulating properly and is stuck closed?


Well, no actually; the switch and voltage are doing exactly what they should. It’s just that these results are unexpected  because there's a misunderstanding about how the simulated circuit differs from a real circuit.


No real switch has an infinite OFF state resistance but similarly, there is no such thing as a real open circuit that presents an infinite load impedance.


The Voltage and Current Controlled Switches and the Static Switches in EasyEDA are not ideal: they all have a finite OFF resistance. For the voltage and current controlled switches, the OFF resistances are specified by the user editable R(off)(Ω) parameter in the right hand panel with a default value of 1GΩ. The Static Switches have a fixed 10GΩ OFF resistance. In either case these resistances are large but certainly not infinite.


However, the effective resistance to ground at the Output node using a Voltage Probe or plot expression, really is infinite. Therefore when operating into an infinite resistance load there would be no difference between the ON and OFF state voltages at the Output node.


Note that if a load resistance of 1GΩ were to be connected from the Output node to ground, then there would be a clear ON/OFF state difference.


This is illustrated in the following simulation:


>[EasyEDA switches are not ideal](https://easyeda.com/editor#id=4dc153fdd97747ba943899a48549e2c3)

Some further examples of the effects of finite switch resistances are illustrated in this next simulation:


>[Effects of finite switch resistances](https://easyeda.com/editor#id=84e648caef3a4bd2a21399731fde1f39)

Note that, in ngspice, the Ron and Roff values used in switches can be set such that Ron > Roff. This is a useful way to invert the logic sense of a switch.

At this point it is worth noting that if it is important that the simulation results are as close as possible to those expected to be observed when probing a real circuit using real test equipment, it is sometimes useful to place a realistic load on wires (nets) in the simulation schematic where voltage measurements are to be made in the real circuit. Similarly for current measurements, realistic ammeter insertion impedances should be connected in series with the wire. To avoid unnecessary loading of the simulated circuit however, only place such loads in the locations where external measurement devices are to be connected to the real circuit and only in the same numbers as there are measurement instruments being used at the same time. For example, if there are two oscilloscope probes connected to a circuit but one of them is moved around, only connect loads representing simulated oscilloscope probes to two places in the simulated circuit. If different places need to be probed then move the simulated probes and rerun the simulation.

#### DC paths through Voltage and Current Sources

This section is about the DC paths through Voltage and Current Sources.

* Voltage sources in ngspice (including independent V and dependent B and E voltage sources) have zero source resistance and have no current limit. The output voltage will be constant for any load current. This is true when sourcing or sinking current. sinking. This is not the same behaviour as regulated and current limited bench power supplies set to give a constant voltage output. Except for specialised supplies such as Source Measure Units, bench supplies can usually only source currents for positive outputs or sink currents for negative output voltages, up to some current limit set by the user.

 * Voltage Sources in ngspice therefore have a DC path through them.

* As a consequence of their zero source resistance, in the same way that damagingly high currents will flow if real batteries are connected in parallel without some resistance between them, voltage sources in simulation schematics cannot be connected in parallel without some resistance in series between them. This is true even if they are set to exactly the same voltage. Attempting to do so will cause the simulation run to fail with an error.

* Similarly, in the same way that damagingly high currents will flow if an inductor is connected directly across a real power supply without some resistance between them, inductors in simulation schematics cannot be connected directly in parallel with voltage sources without some resistance in series between them.  Attempting to do so will cause the simulation run to fail with an error.

* Current sources in ngspice (including independent I and dependent B and F sources) have an infinite source resistance and have no voltage limit. The output current will be constant for any load impedance and voltage across the current source. This is not the same behaviour as regulated and current limited bench power supplies when they are set to give a constant current output. Except for specialised supplies such as Source Measure Units, bench supplies can usually only source currents up to some maximum positive voltage at the output or sink currents down to some minimum negative voltage at the output, as set by the user.

 * Current Sources in ngspice therefore do not have a DC path through them.

* As a consequence of their generating a constant current through an infinite source resistance, in the same way that damagingly high voltages can be generated if two real current sources are connected in series without some finite resistance across each source, current sources in simulation cannot be connected in series without some finite resistance connected in parallel with each source. Attempting to do so will cause the simulation run to fail with an error.

* In simulation, connecting a capacitor in parallel with a current source generating a current, I, without also connecting a resistor, R, in parallel, will cause the voltage on the capacitor to ramp towards infinity. Even with the resistor in parallel, the voltage will ramp to I*R which may still be a large voltage. If such a circuit exists in a simulation schematic then, unless it is shorted out by a switch with some suitably low value resistance or set to some initial voltage, the voltage across the capacitor will already have ramped towards infinity at time t=0, i.e. as the simulation starts. This can lead to unexpectedly high voltages right from the start of a simulation.

#### The effects of adding DC paths

This section is about creating DC paths and some of the effects they can have.

* A favourite of elementary electrical engineering classes and an example of a very tricky problem to solve using a simulator is a circuit that has two capacitors in series. This must have a DC path to ground from the common point between the two caps but the path to ground does not have to be direct. It can be via other elements in a circuit. For example if one end of one of the capacitors is connected to ground with the other end of the other capacitor connected directly to a grounded voltage source or to a Thevenin Source (a voltage source in series with a resistance) or to a Norton Source (a current source in parallel with a resistance) then placing a single high value resistor in parallel with either of the capacitors or simply from the junction of the two capacitors to ground would be sufficient.


The following simple example will not run because there is no DC path to ground from the common node B, between the two capacitors:

>[Capacitors in series 01](https://easyeda.com/editor#id=c9feb45df999407eaedfd43ce6e5d58d)

Because the top end of C1 already has a DC path to ground through the ammeter and voltage source and the bottom end of C2 is grounded, simply adding a resistor to ground from the junction of the two capacitors at node B will allow this simulation to run. It will however, show voltages across the capacitors that can be confusing if the effect of the DC path resistance is not clearly understood:

>[Capacitors in series 02](https://easyeda.com/editor#id=6192cbb5af5f4ae9878680c2d924f737)

* Resistors placed across capacitors to provide a DC path can be scaled so that the R*C time constant that they will create with the capacitors is very large compared to the time interval over which a Transient simulation is to be run. Another way to look at this for an AC Analysis is that the 1/(2*pi*R*C) frequency that they form is far outside the frequency range of interest.


>
The value of these resistances can be anywhere between milliΩ (1e-3 Ω) up to 1G Ω (1e9 Ω). In many cases the values can be smaller or larger than this range but in some circuits that can lead to simulations failing with errors. This is usually because the ratio of the largest to the smallest voltages or currents in the circuit is too high for the simulator to handle. As a general rule, keeping the ratio between the smallest and the largest component value for any given type of passive component to no more than 1e12 should help avoid this sort of simulation failure.

* It must be noted however that whilst a purely theoretical analysis of the voltages across capacitors in series due to a current flowing through them based on Q=I*t=C*V, may yield sensible values, setting up both real and simulated circuits to demonstrate this can be quite challenging. Voltage measurements in real circuits can be difficult whilst the need for a DC path in simulations can present different but no less tricky problems.

Any attempt to try to measure the voltages across a pair of capacitors in series using DC sources will either end in a failed simulation, because here are no DC paths to ground, or will just yield the steady state DC voltages across the resistors used to create the necessary DC paths to ground.

There are a couple of ways to measure capacitor voltages in this sort of circuit. As illustrated below, the simplest is to replace the DC voltage source with a PULSE source configured to generate a fast edged step from 0 to 1V. As long as the RC time constant of the DC path resistance and the capacitors is large compared to the simulation stop time then the voltage across each capacitor will be equal to that given by a theoretical analysis and will be defined by the ratio of the capacitors.

>[Capacitors in series 03](https://easyeda.com/editor#id=51f94aeaa55a4050a233577ea224259a)

Another possibility is to apply a linearly ramped DC voltage of 1V/s across the capacitors in order to generate a constant current through them. The voltages across the individual capacitors will then rise in inverse proportion to their capacitances. By dividing these voltage by the time, a voltage can be generated that is equal to those which would be observed in a purely theoretical analysis of a 1V DC source with two capacitors in series thrown across it.The following example illustrates a way to actually measure the capacitances. It also introduces some of the more advanced uses of the B source which will be covered in more detail later on.

>[Capacitors in series 04](https://easyeda.com/editor#id=e6820188c1354d3182345c97d9ed5fb7)

* Similarly, a transformer coupled circuit where the primary side is driven from mains live and neutral and one side of the secondary circuit is connected to earth (which is probably where the ground symbol would be placed in the circuit diagram), must have a DC path back to this ground from one or both ends of the transformer primary (or from a centre tap if one is available).


>
Similarly to placing resistors across capacitors, DC path resistors used with inductors can be scaled so that the R/L time constant that they will create is very large compared to the time interval over which a Transient simulation is to be run. Another way to look at this for an AC Analysis is that the 1/(2*pi*R*C) frequency that they form is far outside the frequency range of interest. Capacitors.


>
Another example of where very high value resistors would be added is in transformer coupled datacommunications networks such a 100BaseTx or 1000BaseT Ethernet.

>Here, the connections between the two transceivers are floating and so have to have DC paths to ground added to keep the simulator happy. Using resistances that are high in comparison to the network cable characteristic impedance and hence termination resistance is important in order not to introduce an impedance mismatch and so disrupt the signal integrity. In practice it is simplest therefore to add two resistors: one from each of the two signal wires to ground. This preserves the symmetry of the signalling on the wires and doubles the effective resistance between them.


>
In many transformer coupled circuits, the simplest solution is to ground one side of both the primary and the secondary sides of the circuit. This may look strange because the circuits are no longer galvanically isolated by the transformer but - as long as the reason for connecting the circuits this way is clearly indicated in the schematic (and removed or otherwise modified before passing into PCB layout!) - then it is a simple and very useful solution. Not only does it remove any problems with how large or small the DC path resistor has to be, it also refers the voltages on both the primary and the secondary sides to ground and so simplifies probing of many of the voltages on both sides of the transformer which might otherwise have to be probed differentially.


>
Some examples of this use of the ground return path resistor can be seen in the following collection of examples of transformers and coupled inductors, including a simple example of an open loop flyback converter:

>>[Transformers and coupled inductors](https://easyeda.com/editor#id=|7ab8bb1d930e43a7bfdc3f28504f3010|34d761aaa3904d7d92a4321ec39a76f0|98eee55c886b490fa8d5213d0db59237|a96881d710fe4909b2d24d7c7204cbe6|fb0f57da838b41b2b50cd05c3275028b|add48225f8b043c1b637d479df0a1f87) 

>>[Introduction to transformers in EasyEDA](https://easyeda.com/editor#id=fb0f57da838b41b2b50cd05c3275028b)

>>[Transformers and coupled inductors 1](https://easyeda.com/editor#id=34d761aaa3904d7d92a4321ec39a76f0)


>
>[Transformers and coupled inductors 2](https://easyeda.com/editor#id=98eee55c886b490fa8d5213d0db59237)


>>[
Transformers and coupled inductors 3](https://easyeda.com/editor#id=7ab8bb1d930e43a7bfdc3f28504f3010)


>>[
Transformers and coupled inductors 4](https://easyeda.com/editor#id=add48225f8b043c1b637d479df0a1f87)

 
>
>[Open loop flyback converter](https://easyeda.com/editor#id=a96881d710fe4909b2d24d7c7204cbe6)

* To avoid confusion between passive schematics intended to be passed to PCB layout and simulation schematics that may have had DC path resistors added, it is a good idea to clearly identify any resistors added to a schematic soley to provide a DC path to ground. This can be done using resistor names such as RDCPATH1 or by labelling them for example as *For simulation only.*

* It must be remembered that all voltages probed in a schematic are with respect to ground. This is particularly important to remember when probing signals that are floating, such as the transformer coupled examples discussed above. This is when B or E Sources can be used to probe two floating voltages and subtract them to simply generate the difference between them.

#### Common problems with DC paths

A DC path to ground is often provided by the rest of the circuit but here are some cases that are often overlooked:

* All current sources (independent I and dependent B and F sources) are ideal: they have an infinite DC resistance (and AC impedance) and so do not have a DC path through them. Connecting a current source across a capacitor with one side grounded will throw an error even if the current source is set to zero (the capacitor voltage would ramp to infinity if a non-zero current were set and that would throw a different error!). So a resistor must be connected across the current source, to provide the DC path to ground to the other side of the current source / capacitor. A similar problem arises if two current sources are connected in series even if the two currents are identical (if they're not then the common node flies off to infinity again);

* Switches have their own internal DC path between the switch terminals because they have finite OFF resistances. However, **voltage controlled switches** do not have a DC path between their control inputs.

* **Current controlled switches, Current Controlled Current Sources (CCCS)** and **Current Controlled Voltage Sources (CCVS)** all have a zero resistance short circuit between their control inputs. At first sight it might appear that connecting the output of a current source to the input of a current controlled switch would not cause a problem because the switch control input places a short circuit across the current source output. There is, however, no DC path to ground from the these connections so a resistor must be placed from one of the current controlled switch input pins to ground. If the current source output/switch control input part of the circuit is not connected to anything else then the resistor can be replaced by a connection to ground.


This is illustrated by the placement of the RDC_PATH_TO_GROUND 1k resistor connected to output side of the CCCS, F1, and input side of the current controlled switch W1 in the example below:

>[Controlling EasyEDA switches](https://easyeda.com/editor#id=2612258a82ca48bf9b39b31834a2cff0)

* Capacitors (unless using the more advanced options in ngspice) are ideal: they have no parasitic (leakage) DC resistance in parallel with them. This is why both ends of a capacitor must have a DC path to ground either through the external circuit or explicitly by adding a resistor;

* Although the primary and the secondary or secondaries of transformers have DC paths, there is of course no DC path from primary to secondary. This must be added either by connecting one side of the primary and of the secondary to ground directly or through a resistor.

* Voltage sources (including independent V and dependent B and E voltage sources) have the opposite problem. They are ideal so they have zero resistance. The same is true for simple inductors. If you connect voltage sources directly in parallel then ngspice will throw an error even if the voltage sources are set to the same value (if they're not then an infinite current would flow and that would then throw a different error). The same problem arises if you connect a voltage source directly in parallel with a simple, ideal, inductor because the voltage source tries to drive an infinite current through the inductor.


This problem often occurs when driving a transformer from a voltage source. Adding a small series resistance fixes this little gotcha (in practice there will always be a finite winding resistance anyway!).

### Components are connected by netnames

It is important to understand that although components in a schematic can be shown joined by wires or by netlabels, in a spice netlist they are joined by purely by the net names given to them either automatically by EasyEDA or manually by the user placing netlabels. This includes nets joined by any of the three NetFlag GND ground symbols. It also includes nets joined by the Net Port, NetFlag VCC and NetFlag +5 symbols as illustrated below:

>[Nets can be joined by netnames 01](https://easyeda.com/editor#id=f0813f811ee948468bfc80cc3a9bcbb0)

It is equally important to understand that when a wire between two components in a schematic is broken then - unless the wire on both sides of the break is explicitly given the same netname by manually placing netlabels with the same name - then *the wires on each side of the break will have different netnames* because even though one side may already have a manually assigned netname, the other side will automatically have a new and arbitrary netname assigned to it by EasyEDA.

The significance of manually assigning net names will become apparent a little later when looking at how to probe voltages and using the voltage on nets in expressions for B sources.

>[Nets can be joined by netnames 02](https://easyeda.com/editor#id=92e7ef55c10340289f8fc4637f70ba64)

As just illustrated, breaking a wire creates two segments of wire that are no longer connected to each other. This is because EasyEDA automatically assigns different netlabels to each end of a broken wire.

To rejoin the connection, add netlabels with the same name to each segment of the broken wire. NetPorts and NetFlags can be placed anywhere on a net but take care that the little grey connection dot is placed onto the wire.

To avoid accidentally connecting nets together that are not intended to be connected when manually assigning netlabels, take care to ensure the netnames assigned are unique to each net. For instance, in the following example, using the name 'mid' instead of 'ammeterneg' would connect the negative side of A1 to the 'mid' net and would short out R1.

>[Nets can be joined by netnames 03](https://easyeda.com/editor#id=7b9a788a8dd94dd1b09cf96b83136525)

# Probing signals

After spending ages building a schematic the time has finally arrived: the first simulation is run. The **Simulation Results…** window pop opens and there it is …

Nothing.

No warnings.

No error messages.

No dire messages about *Timestep too short* or *Trouble with node X*

What's gone wrong?

The most likely cause is one of the most overlooked beginners' mistakes: there are no signal probes in the schematic. The simulation has run fine. It just didn't produce any results simply because it had not been asked to!

In order to view any useful output from a simulation, the circuit must have at least one voltage probe or one ammeter in the circuit. In basic simulations these will be the Voltage Probe and Ammeter symbols from the EasyEDA Libs. In more advanced simulations, these can be implemented using a `probe` command. In either case, at least one type of probe must exist in the simulation schematic. If no probe is present, the simulation will run but the **Simulation Results…** window will be empty and no WaveForm window will open.

## Probing voltages

All voltage measurements in real circuits are actually measurements of voltage differences. In many cases such as when probing a voltage using an oscilloscope probe, it is easy to forget that the voltage being measured is, in reality, the difference between the voltage at the probe tip and wherever the probe ground lead is connected. In the same way it is easy to forget that probing a single ended voltage in a simulation schematic is with respect to wherever the ground node has been placed.

* A common mistake, however, is to attach a voltage probe to ground.

 

>In spice simulations, all voltages are referred to ground so not only is there no need

to attach a Voltage Probe to the ground net, in fact doing so will throw an error in the simulation.

In a real circuit, probing a voltage between any two points places a resistive load between them. With a good quality voltmeter that resistance may be very high, in the order of hundreds of MegΩ. With an x10 oscilloscope probe it will be 10MegΩ. There will be some stray capacitance across that resistance. There will also be stray lead inductances. If the voltage being measured is an AC signal then impedances due to these stray and parasitic components will also load the circuit.

Note that in simulations, voltage probes present an infinite resistance and have no stray capacitance or inductance. In effect, voltage probes have an infinite bandwidth.

The following example illustrates some of the probing techniques described above:

>[Probing voltages 01](https://easyeda.com/editor#id=f952fa5da1a44c18a4138ad6fbe185e0)

The following example shows a number of ways to measure voltages with respect to ground or differentially using;

* The EasyEDA Voltmeter;

* An `E` source (a.k.a. Voltage Controlled Voltage Source or VCVS) with a Voltage probe to probe the output;

* A `B`, source (a.k.a. behavioural or dependent source) configured as a VCVS using a Voltage probe to probe the output.

The schematic also demonstrates the importance of:

* Giving voltage probes names that are identical to the nets to which they are attached;

* Naming all nets in a schematic;

>[Probing voltages 02](https://easyeda.com/editor#id=2b160f33e20147dfb7948085ca14d85a)

## Probing currents

In a real circuit, probing the current in a wire places a resistive load between them. This will cause some voltage drop across the ammeter. With a good quality ammeter that voltage drop may be very low, in the order of millivolts. There will be some stray capacitance across the insertion resistance and from the ammeter connections to ground. There will also be stray lead inductances. If the current being measured is an AC signal then impedances due to these stray and parasitic components will also load the circuit.

Note that in simulations, current probes present zero insertion resistance and have no stray capacitance or inductance. In effect, current probes have an infinite bandwidth.

The following example shows a number of ways to measure currents with respect to ground or differentially using;

* As a current using the Ammeter symbol; 

* As a linearly scaled voltage using an H Current Controlled Voltage Source (CCVS) (or an F Current Controlled Current Source (CCCS) with a resistor); 

* As a linearly scaled current using an F Current Controlled Current Source (CCCS) driving an Ammeter; 

* As a voltage that can be an arbitrary function of the current flowing through a 0V Voltage Source using a BV source (or a BI source with a resistor); 

* As a current that can be an arbitrary function of the current flowing through a 0V Voltage Source using a BI source driving an Ammeter.


Note however, that although a 0V source can be used to *monitor* a current, it cannot be used to *measure* a current so that it can be directly displayed in the **Simulation Results…** window or plotted in Waveform.

>[Probing currents 01](https://easyeda.com/editor#id=4ed6a7be4a6d42d8820bb8cd2e360edb)

# Advanced probing and simulation control

So far, the examples have used three different ways of running the simulations:

* The basic way of setting up and running a simulation using **Tools > Simulation > Simulate this Sheet... >** option to open the 'Run your simulation' dialogue and then select the type of analysis to run.

* Using the **CTRL+R** Hotkey as a shortcut to the `Run your simulation` dialogue.

* Using `spice directives` to run simulations straight from the **CTRL+R** Hotkey so that, with a few simple key strokes, it is easy to switch between several different simulations from a single simulation schematic.

The following sections will show how to do more advanced signal probing which, when combined with the use of spice directives to control simulations and the flexibility of the

>**Text type > spice/comment**

text attribute to switch between sets of probing and simulation commands, takes simulation to the next level.

## The `probe` command

The section on probing signals showed how to probe voltages and currents in a schematic by adding symbols to the schematic in much the same way real pieces of test equipment such as DVMs and scopes and ammeters can be used to measure voltages and currents in a real circuit.

This section and the associated examples will introduce the 'probe' spice directive to measure voltages, currents, powers and more in a circuit.

This section reinforces the importance of naming all nets as discussed earlier.

### What the `probe` spice directive does

The `probe` spice directive:

* Replaces voltage probes;

* Provides an alternative way to probe currents simply by placing a 0V Voltage source anywhere a current is desired to be measured;

* Allows arbitrary functions of any combination of voltages and/or currents to be carried out such as addition, subtraction, scaling, division, raising to powers and multiplying voltages and currents to calculate power dissipation.

* Allows several `probe` statements to be put into a single schematic and using:


>**
Text Attributes > Text type > comment/spice**


provides an easy way to select between probing different sets of measurements by switching the state of probe statements between `comment` (simple inactive text which is ignored by the simulator) and `spice` (interpreted by the simulator as active spice directives).

### The syntax of a `probe` directive

* The `probe` directive comprises the keyword ‘probe’ followed by a space separated list of voltages, currents and expressions;

* All probed signals must be in a single line following the keyword ‘probe’, with no line breaks;

* Voltages are expressed in the form: V(netname), where 'netname' is the name of the net on which the voltage is to be probed;

* Currents are expressed in the form: I(V_source_name); where `V_source_name` is the name of the voltage source through which the current to be probed is flowing;

* Any combination of voltages and currents can combined together in an expression;

* Any voltage and current can be negated by multiplying it by -1 but the negated value must be enclosed in brackets to avoid confusion with an arithmetic subtraction from a preceding value in the list of values in the probe directive. For example to probe a voltage and a polarity reversed current as two separate values, the porbe directive must be written as:

>>**probe V(netname) (-I(V_source_name))**


>
and not:

>>**probe V(netname) -I(V_source_name)**


>
because the latter form will actually probe the voltage V(netname) minus the current I(V_source_name), i.e. {V(netname)-I(V_source_name)} and not the two individual values of V(netname) and -I(V_source_name).

* Inline expressions can be written with or without enclosing brackets, however, for clarity and the avoidance of misinterpretation as described in the preceding paragraphs, it is good practice to use enclosing brackets.


>
For example to probe the power in a grounded resistor due to the voltage across it and the negated current through it is clearest to write the expression as:

>>**(V(netname)*-I(V_source_name))**

>or:

>>**(-V(netname)*I(V_source_name))**

>rather than:

>>**-V(netname)*I(V_source_name)**

* The difference between two voltages:

>>**V(A)-V(B)**


>
can be expressed as:


>>**
V(A,B)**


>
Therefore, to probe the difference between two voltages, V(a) and V(b), a probe directive can be added to the schematic to do the subtraction. Like this:


>>**
probe (V(A)-V(B))**


>
or:


>>**
probe V(A,B)**

>The same is true for current differencing:

>>**I(VIMON1)-I(VIMON2)**

>can be expressed as:

>>**I(VIMON1,VIMON2)**

>Therefore, to probe the difference between two currents, V(a) and V(b), a probe directive can be added to the schematic to do the subtraction. Like this:

>>**probe I(VIMON1)-I(VIMON2)**

>or:

>>**probe I(VIMON1,VIMON2)**

These points are illustrated in the following sections.

### Using the 'probe' command to make measurements

The examples, [Probing voltages 01](https://easyeda.com/editor#id=f952fa5da1a44c18a4138ad6fbe185e0), [Probing voltages 02](https://easyeda.com/editor#id=2b160f33e20147dfb7948085ca14d85a)] and [Probing currents 01](https://easyeda.com/editor#id=4ed6a7be4a6d42d8820bb8cd2e360edb) have shown how to probe voltages and currents in a schematic by adding symbols to the schematic in much the same way real pieces of test equipment such as DVMs and scopes and ammeters can be used to measure voltages and currents in a real circuit.

This next example introduces the 'probe' spice directive which can be used to measure voltages, currents, powers and more in a circuit.

>[Using the probe command](https://easyeda.com/editor#id=8e50c2b0835f4f49b73d35a5c5747f6d)

### Probing instantaneous power

The 'probe' directive can be used to measure power by probing the voltage difference across a device and the current through it and then simply multiplying the two signals together using an expression.

So, for example, the total power in a device such as a bipolar transistor, is given by the sum of the collector-emitter voltage times the collector current plus the base-emitter voltage times the base current.

The expressions in the example below probe the power dissipation in R1, total power drain from V1 and the sum of the powers in R1, R2 and R3.

>[Probing instantaneous power](https://easyeda.com/editor#id=04ac938e2cf34816a45b790a23b4cb37)

### Probing resistances and conductances

Resistance is measured by probing the voltage difference across a device and the current through it and then simply dividing the voltage by the current using an expression.

Conductance is measured by probing the the voltage difference across a device and the current through it and then simply dividing the current by the voltage using an expression.

The expressions in the example below probe the resistance and the conductance of R1.

>[Probing resistance and conductance]{https://easyeda.com/editor#id=8177da5abf604aeb8381dc9bc1bd5fd4}

## Using CTRL+R to run a simulation directly

This section introduces the idea of placing the simulation directive directly into the schematic.

This makes running a simulation even easier because instead of using the:

>**CTRL+R > Select simulation type > Run **

type of key sequence to run a simulation, the key sequence simplifies to just:

>**CTRL+R **

Not only does this make running a simulation easier but it also extends the idea - introduced in `The 'probe' command` - of being able to quickly and easily change the selection of traces to be displayed in WaveForm, to being able to change the actual simulation to be run as well.

(Typing the simulation directive directly into the schematic is also a necessary step to allow the `let` and `print` commands to work but this will be described in `Using the 'let' command`.)

Adding the simulation directive directly into the schematic is easy.

All that has to be done is to type the directive as a line of text in the schematic and then do:

>**Text type > spice **

to turn the passive text (blue font) into an active spice directive (black italic font).

Note that one and only one simulation directive can be active for any one simulation run.

The example below illustrates how to do this:

>[Using CTRL+R to run a simulation directly](https://easyeda.com/editor#id=5a5a9904773c402785239f586969ac9b)

## The `let` command

In `The 'probe' command` it was shown how voltage, current, power, resistances and more can be probed using V(netname), I(Vsource) and expressions made up from these terms in a probe command.

This section introduces the 'let' spice directive to do the same job but at the same time, make the display of the results clearer.

Note that the `let` command will not work with simulations started using:

>**Tools > Simulation > Simulate this Sheet... > Select simulation analysis > Run**

or:

>**CTRL+R > Select simulation analysis > Run**

Instead, the simulation directive must first be placed directly into the schematic, as described in `Using CTRL+R to run a simulation directly`.

Then the `let` command must be typed into the schematic in a text box which is then made active to turn it into a spice directive:

>**Text Attributes > Text type > spice**

as illustrated below:

>[Using the let command](https://easyeda.com/editor#id=5adb22fdd15744e2afde48c3aa6efe0e)


# Configuring Voltage and Current Sources

EasyEDA Libs provides a range of what are referred to in ngspice as **Independent Sources**.

These are Voltage and Current Sources whose outputs are defined by a list of values or parameters. The outputs do not depend on anything else.

These sources have already been discussed in terms of their DC source resistances and DC paths.

In most of the examples so far, they have been used to provide DC supply voltages either as ideal voltage sources or as Thevenin or Norton Sources.

Their use to provide time domain (time varying) signals has been introduced in the examples about transformers but has not so far been explained.

This section describes in detail how any dependent source can be set up to provide the following types of signal sources:

* SINE or SIN: a sinusoidal signal;

* PULSE: a general pulse waveform;

* EXP: a single pulse with exponential rising and falling edges;

* SFFM: (Single Frequency Frequency Modulated) a single sinusoidal carrier, frequency modulated by single sinusoidal frequency;

* AM: (Amplitude Modulated) a single sinusoidal carrier, amplitude modulated by a single frequency;

* PWL: (PieceWise Linear sources} an arbitrary waveform source with signals created as a list of times and levels with the signal linearly interpolated between each time point.

Although the examples in this section only illustrate how to configure Dependent Voltage Sources, Dependent Current Sources are configured in exactly the same way.

## Configuring the SIN or SINE option

Configuring the SINE option to create an unmodulated, single frequency sinusoidal signal source.

>[Spice Sinusoidal Source](https://easyeda.com/editor#id=5e3d25de3492487b88275e38c4620239)

## More ways to use the SIN (or SINE) option

>[Spice Sinusoidal Source: more examples](https://easyeda.com/editor#id=14f65f0d5867457aa55952b6cc1e7d05)

## Configuring the PULSE option

Configuring the PULSE option to create a pulse signal source.

>[Spice PULSE Source](https://easyeda.com/editor#id=d49a7278feef4be2b72d851765f3acbb)

## More ways to use the PULSE option

>[Spice PULSE Source: more examples](https://easyeda.com/editor#id=b390ba5169074c11bc7ea770555c7b81)

## Configuring the EXP option

Configuring the EXP option to create a single pulse source with exponential rising and falling edges.

>[Spice EXP Source](https://easyeda.com/editor#id=cb23023471ee4496938c1620db02ec8e)

## Configuring the SFFM option

Configuring the SFFM option to create a simple, single frequency, frequency modulated sinusoidal signal source.

>[Spice SFFM Source](https://easyeda.com/editor#id=5e8a32ab1cf44f9aa8500fd82536e54f)

## Configuring the AM option

Configuring the AM option to create a simple, single frequency, amplitude modulated sinusoidal signal source.

>[Spice AM Source](https://easyeda.com/editor#id=fe878e6597464623bdb72fa9314a2bd9)

## Configuring the PWL option

Configuring the PWL option to create an arbitrary piecewise linear waveform signal source.

>[Spice PWL Source](https://easyeda.com/editor#id=082bd08b1685456ab5edc1dbd579c797)

## Configuring the AC source option

It can be quite hard to visualise what the Amplitude and the Phase settings in the AC Source options of the Independent Voltage and Current Sources really mean when the signals in an AC Analysis cannot be viewed in the time domain in a Transient Analysis. To try to help visualise these settings and what they represent, the following couple of examples demonstrate the settings in ways that can be related back to their equivalents in the time domain.

The first example shows how more than one AC Source can be configured in a circuit to represent different signal sources at the same frequency but with different phases. The example also shows how the phase settings relate to the same signals in the time domain.

In this example both AC Sources are set to the same amplitude of 1. They could be set to different amplitudes: try it and compare the results with the same amplitude changes in the time domain part of the signal sources.

>[Configuring AC Sources 01](https://easyeda.com/editor#id=eb95943b02d640e9917726239403694e)

Note, however, that the AC Analysis assumes that the circuit is perfectly linear so even if an AC Source amplitude 100 were to be specified, the output would still look as if it came from a perfectly linear circuit. Compare that with what happens if the time domain parts of the sources are set to 100!

The DC offset of the inphase AC Source in this example is important because it biases Q1 into a range where both the emitter and collector swings are operating in the linear region.

This can clearly be seen by probing V(Q1E) and V(Q1C) in a Transient Analysis. If the DC Offset is increased, eventually the V(Q1C) as V(Q1E) rises will until they meet as Q1 saturates and V(Q1E) starts to pull V(Q1C) back up again. At the point where this happens the small signal gain of the collector output passes through zero and then becomes a non-inverting gain of somewhat less than unity.

If the DC offset is reduced to near ground or even below it, Q1 is cut off so both the collector and the emitter output small signal gains fall effectively to zero. Again this can clearly be seen in a Transient Analysis.

What is not so obvious is that although these effects still occur in the AC Analysis, because they are represented in the frequency domain, they can sometimes be hard to interpret.

So, the information to take away from this is that if an AC Analysis seems to be showing a lower than expected gain then it is worth checking that the DC operating point of the circuit is not forcing some part of it into saturation or cutoff. One example of this is incorrectly biasing an opamp input so that the output has hit one or the other of the supply rails. Forgetting to connect up a power supply rail is another common mistake.

It must also be understood that although any number of AC Sources can be placed in a circuit, each with their own amplitude and phase, all the sources will operate at exactly the same frequency as this is determined by the AC Analysis settings and not by the sources themselves.

In a circuit with several Independent Sources in it, AC sources can simply be added to, removed from or moved around it just by adding the AC amplitude and phase values to the required source. So in the example above, the response of the inphase and out of phase side of the all pass network can be observed simply by setting one AC Source or the other to have zero amplitude or just by deleting the AC parts of the Source configuration.

Another example of this might be that the frequency response of an amplifier from signal input to output can be plotted using an AC Source at the input source whilst the frequency response of the amplifier from power supply ripple to output can be plotted by swapping the AC Source settings to the voltage source being used for the power supply.

The second simulation also shows how more than one AC Source can be configured in a circuit to represent different signal sources at the same frequency but this time with different amplitudes and phases. This example also shows how the amplitude and phase settings relate to the same signals in the time domain.

>[Configuring AC Sources 02](https://easyeda.com/editor#id=6308cf710e44429bb97b26ec72418b01)

# Setting up Analyses

## What are Analyses?

An analysis is simply the instruction to the simulator telling it what type of simulation to carry out on the spice netlist.

There are several different types of analysis that can be carried out when a simulation is run.

EasyEDA supports a subset of the spice analyses that are available in ngspice. The supported analyses supported by the Simulate... dialogue box (accessed via **Tools > Simulation > Simulate this Sheet** or **Simulate this Project** options or directly via **CTRL+R**) are described below.

### SPICE Analyses available from the Super Menu> Miscellaneous > Simulate menu

Selecting **Tools > Simulation** opens the Simulation options menu.

* **Simulate this Schematic**


This is to run a simulation on a single schematic sheet.

* **Simulate this Project…**


This is to run a simulation on all the schematic sheets in a project.


Note that the component prefixes (reference designators) must be unique across all schematic sheets: i.e. there must be no duplicate reference designators.


Attempting to run a simulation on any sheet or collection of sheets containing duplicate reference designators will generate the Prefix conflict error'.

By doing:

>**Tools > Simulation > Simulate this Schematic… / Simulate this Project…**

the following SPICE analyses can be run from a simple dialogue box. For more information about what they do, please scroll down to the relevant sections.

1) DC op pnt

2) DC Transfer

3) DC Sweep

4) AC Analysis

5) Transient

### SPICE Analyses and Control Statement Syntax

The following SPICE analyses can also be entered directly into a text box in a schematic.

Several analysis statements can be entered in a single schematic but one and only one can be made active for any one simulation run. To make an analysis statement active, do:

>**Text Attributes > Text type > spice**

To make an analysis statement inactive, do:

>**Text Attributes > Text type > comment**

They can then be run simply by doing:

>**CTRL+R**

Several analysis statements can be entered in a single schematic but one and only one can be made active for any one simulation run.

#### 1) OP: Perform an Operating Point Analysis

General form:

>**op**

Example:

>**op**

Causes SPICE to perform an operating-point analysis to determine the the quiescent state of the circuit with inductors shorted and capacitors opened. The results of this analysis are used to calculate values for the the linearised, small-signal models of nonlinear devices.

#### 2) TF: Perform a DC Transfer Function Analysis

The dc transfer function analysis portion of SPICE computes the following small signal characteristics:

* the ratio of output variable to input variable (gain or transfer gain)

* the resistance with respect to the input source

* the resistance with respect to the output terminals

The TF statement can be used to find the Thevenin small signal equivalent resistance. (The Thevenin voltage is given by the node voltage at the open circuit terminal, as a result of the OP statement).

General form:

>**tf OUTvar inSRC**

Examples:

>**tf V(5, 3) VIN**

>**tf I(VLOAD) VIN **

The TF command defines the small-signal output and input for the DC small-signal analysis. OUTvar is the small-signal output variable and inSRC is the small-signal input source. If this line is included, SPICE computes the DC small-signal value of the transfer function (output/input), input resistance and the output resistance.

#### 3) DC: Perform a DC-Sweep Analysis

During a DC-sweep analysis SPICE steps the value of a specified independent voltage or current source over the user-specified range and performs an operating point analysis at each value. This permits the evaluation of the DC transfer function, and also provides a mechanism for plotting the characteristic curves of devices and models.

General form:

>**dc Source-Name Vstart Vstop Vincr >[ Source2 Vstart2 Vstop2 Vincr2 ]**

Examples:

>**dc vin 0.25 5.0 0.25**

>**dc vin 0 10 .5 vgs 0 5 1**

>**dc vce 0 10 .25 ib 0 10u 1u**

>**dc R1 0 1k 100**

>**dc TEMP 0 100 1 **

The parameters define the dc transfer-curve source and sweep limits. Source-Name is the name of an independent voltage or current source, a resistor or the circuit temperature. Vstart, Vstop, and Vincr are the starting, final, and incrementing values respectively. The first example causes the value of the voltage source vin to be swept from 0.25 volts to 5.0 volts in increments of 0.25 volts. A second source (Source2) may optionally be specified with associated sweep parameters. In this case, the first source is swept over it's range for each value of the second source.

It is worth highlighting that the DC Sweep Spice Analysis allows not just voltage and current sources to be swept but also temperature and resistances because Source-Name can also refer to a resistor in the circuit or to the keyword TEMP meaning temperature in degrees Celcius.

The following simulations illustrate sweeping:

* a voltage source;  


>[Plot and compare diode forward currents vs. voltage](https://easyeda.com/editor#id=127dd766b6404c9194edf073697505a5)

 

* a resistor value;


>[Sweep a resistor value](https://easyeda.com/editor#id=bf3d3b6a16ad46838b73d8c4b7340974)

* the ambient temperature applied to every component in the simulation:


>[Sweep the ambient temperature](https://easyeda.com/editor#id=75dbcc056ebe4af1ace2b4b70de8f184)

#### 4) AC: Perform a Small-Signal AC (frequency domain) Analysis

The ac small-signal portion of SPICE computes the ac output variables as a function of frequency. The program first computes the dc operating point of the circuit and determines linearized, small-signal models for all of the nonlinear devices in the circuit. The resultant linear circuit is then analyzed over a user-specified range of frequencies. The desired output of an ac small-signal analysis is usually a transfer function (voltage gain, transimpedance, etc). If the circuit has only one ac input, it is convenient to set that input to unity and zero phase, so that output variables have the same value as the transfer function of the output variable with respect to the input.

General form:

>**ac ( DEC | OCT | LIN ) N Fstart Fstop**

Examples:

>**ac dec 10 1 10K**

>**ac dec 10 1k 100Meg**

>**ac lin 100 1 100Hz **

Use:

>'dec' for decade variation, in which case N is the number of points per decade;

>'oct' for octave variation, in which case N is the number of points per octave;

>'lin' for linear variation, in which case N is the total number of points.

Fstart is the starting frequency, and Fstop is the final frequency.

#### 5) TRAN: Perform a Transient (time domain) Analysis

The transient analysis portion of SPICE computes the transient output variables as a function of time over a user-specified time interval. The initial conditions are automatically determined by a dc analysis. All sources which are not time dependent (for example, power supplies) are set to their dc value.

General form:

>**tran Tstep Tstop >[ Tstart >[ Tmax ] ] >[ uic ]**

Examples:

>**tran 1ns 100ns 0ns 2ns**

>**tran 1ns 1000ns 500ns 10ns**

>**tran 10ns 1us 0us 20ns uic **

Tstep is the suggested computing increment.

Tstop is the final time.

Tstart is the initial time.

If Tstart is omitted, it is assumed to be zero. The transient analysis always begins at time zero.

In the interval , the circuit is analyzed (to reach a steady state), but no outputs are stored. In the interval , the circuit is analyzed and outputs are stored. Tmax is the maximum step-size that SPICE uses; try Tmax=(Tstop-Tstart)/50.0 to start with.

The optional keyword 'uic' (use initial conditions) indicates that the user does not want ngspice to solve for the quiescent operating point before beginning the transient analysis. If this keyword is specified, ngspice uses the values specified using IC=... on the various elements as the initial transient condition and proceeds with the analysis. If the .ic control line has been specified, then the node voltages on the .ic line are used to compute the initial conditions for the devices. IC=... will take precedence over the values given in the .ic control line. If neither IC=... nor the .ic control line is given for a specific node, node voltage zero is assumed.

Please see the description below of the .ic control line for its interpretation when uic is not specified.

#### IC: Set Initial Conditions

General form:

>**.IC V(n1)=VAL <V(n2)=VAL> <...>**

Example:

>**.IC V(11)=5 V(4)=-5 V(2)=2.2**

The IC line is for setting initial transient conditions. It has two different interpretations depending on whether the UIC parameter is specified on the .TRAN control line. One should not confuse this line with the .NODESET line. The .NODESET line is only to help DC convergence, and does not affect final bias solution (except for multi-stable circuits). The two interpretations of this line are as follows:

1) When the uic parameter is specified on the .tran line, then the node voltages specified on the .ic control line are used to compute the capacitor, diode, BJT, JFET, and MOSFET initial conditions. This is equivalent to specifying the `ic=...` parameter on each device line, but is much more convenient. The `ic=...` parameter can still be specified and takes precedence over the .ic values. Since no dc bias (initial transient) solution is computed before the transient analysis, one should take care to specify all dc source voltages on the .ic control line if they are to be used to compute device initial conditions.

2) When the uic parameter is not specified on the .tran control line, the dc bias (initial transient) solution is computed before the transient analysis. In this case, the node voltages specified on the .ic control line is forced to the desired initial values during the bias solution. During transient analysis, the constraint on these node voltages is removed. This is the preferred method since it allows ngspice to compute a consistent dc solution.

**Note that the 'uic' option must be used with caution. **


Normally, a DC operating point analysis is performed before starting the transient analysis. The results of this DC operating point analysis provide the initial conditions for the circuit at time t=0.
The 'uic' spice directive suppresses this initialization.


The initial conditions of some circuit elements can be specified on an instance-per-instance basis. For example: transistors can be specified to be in an OFF initial state; switches can be specified to be in an ON or an OFF initial state; the .IC spice directive allows the voltages on nets at t=0 to be specified.


If the 'uic' option is added to a tran spice directive then all specified initial conditions are used.
It is important to realise however that if the 'uic' directive is used without explicitly stating the initial conditions then, because the DC operating point analysis is omitted, default values are assumed. This can cause problems in some simulations because the default values can lead to non-physical initial conditions around a circuit. For example, consider an ideal voltage source connected in parallel to an ideal capacitor. Unless it is specified otherwise, the default initial value of the voltage source is taken as zero. Therefore, the voltage across the capacitor is also zero at t=0. Then, in the first time step, the voltage source is set to the operating output voltage so an infinite current is drawn from it to charge the capacitor up to this operating voltage. The simulator cannot find a short enough time step to make this current finite, and a "time step too small convergence fail" message is issued.


Note that if the 'uic' option is not used then any .IC directives included in the simulation are used anyway.

# Initial conditions and starting up circuits

## Some background and basic start-up techniques

All time domain simulations start at time t=0.

Even though it is possible to start plotting the results of a simulation at some time after t=0, the simulation itself always starts at t=0.

The initial DC conditions of a circuit are completely defined by the initial levels or DC offsets of any sources present in the circuit. So for example a DC power rail that is set to 9V is treated by the simulator as having been at 9V for all time prior to t=0.

Similarly, a SINE source with a -1V DC offset or a PULSE source with an initial level of 1V are treated by the simulator as having been at -1V DC for all time prior to t=0.

Therefore the voltages in a circuit, such as bjt base bias potential dividers and so on, will have been set to DC steady state values for all t<0. Consequently, the voltages across all capacitors and the currents through all inductors in the circuit will have reached their DC steady state values prior to the simulation starting at t=0.

Even if the circuit is an oscillator, prior to t=0 it will have been assumed to be in a stable non-oscillating steady state. At t=0 the circuit will then start from those initial DC conditions. It will then either continue in that steady non-oscillating state or will slowly drift away from the steady DC state and oscillations will build up.

The initial state of oscillators based on a tuned circuit such as phase shift, Wien Bridge and Crystal Oscillators will be defined by their DC bias conditions. If there are no noise sources in the circuit (the default state for all components unless otherwise specified such as resistors defined to have noise contributions) then there is nothing to nudge the circuit away from equilibrium and so it may never start oscillating.

Although in most cases such oscillators will eventually start up due to the 'hidden' noise source which is simply due to the mathematical noise generated by the finite resolution and rounding errors of the calculations carried out in running a simulation, this can take a very long time compared to the time taken to run the oscillator in a stable oscillatory state for a few cycles. Crystal oscillators in particular can take many hundreds of thousands of times the oscillator period to start up and reach a stable state.

To minimise the simulation time spent waiting for an oscillator to start, it is useful to introduce some initial start-up condition to 'kick-start' the circuit into oscillation.

The simplest way to kick-start a circuit into oscillation is to replace a simple DC supply source with a PULSE source set to an initial level of the desired power supply voltage but configured to generate a short pulse of the supply voltage plus or minus some small voltage. So for example a circuit with a 9V supply that is to run for 1ms with a time step of 1us could have a PULSE source set to an initial level of 9V pulsed down to 8.5V for 1us with 100ns rise and fall times. Or an initial level of 8.5V with a delay of 1us before a 100ns rise-time step up to a pulse level of 9V.

The same trick can be carried out using a voltage source inserted into the circuit almost anywhere in the circuit simply to inject a small step or pulse into a bias voltage but it must be remembered that if the voltage step or pulse does not return to 0 after the kick then it will represent an offset voltage in that part of the circuit.

An example of this is in forcing crystal oscillators to start.

Crystal oscillators take a very long time to start up because of the extremely high Q of the crystal.

The same thing is true of their simulations so, to avoid simulations taking too long to run and generating massive data files, they may need to be run in stages with increasing start and stop times but a small (Tstop - Tstart) value.

As discussed earlier, injecting a small step into the supply voltage or an internal node of the circuit can help to start the oscillations a little earlier but the idea of injecting a small step or pulse into a circuit to kick it into life is taken to an extreme in the EasyEDA crystal model.

The technique used in the XTALfast subckt is to include a PULSE source internal to the crystal model to introduce a very high amplitude impulse at t=0 inside the model. This starts the oscillator almost instantly and because an impulse with a very wideband spectrum is used rather than a step (or a sinusoidal burst at the crystals natural resonant frequency), the oscillations start at the actual resonant frequency of the crystal in the application circuit.

The start up time of the example below using the XTALfast subckt can be compared with the same crystal model but with an unassisted start simply by editing the name of the crystal model from XTALfast to XTALnofast.

>[Crystal oscillator using the EasyEDA quick starting crystal model](https://easyeda.com/editor#id=baf90d566e1c4577a3415c4fb71d8e12)

 

The EXP and PWL sources can also be used as kick-starter supply sources.

Most relaxation oscillators such as the classic two transistor astable multivibrator or the 555 timer have two stable states. Oscillation is normally maintained by the circuit switching between these two states however, under DC bias prior to t=0, these circuits often settle into one or the other of these stable states and so are stuck there at t=0. This means that they never start oscillating.

This is an example of a simple RC relaxation oscillator that does not start up by itself:

>[Relaxation oscillator startup 01](https://easyeda.com/editor#id=09069e1dfa4f4a9aa9d0b577af47d631)

This type of circuit may need a rather more vigorous kick to get it started. This can be done using a PULSE source but instead of introducing a small step, the supply is ramped up to the desired supply voltage from 0. So, for example, by setting an initial level of 0 and a pulse level of 9 with zero delay time, with a rise-time of 200us the circuit starts up cleanly up from all internal nodes being at zero:

>[Relaxation oscillator startup 03](https://easyeda.com/editor#id=875a1803aa2e4c89be6bb97582a5bced)

Another possibility - which will be explained in more detail later - is to use an expression that is a function of time in a B source.

For example, this expression in a B source:

>**V=9*(1-exp(-1*time/100u))**

generates a voltage that starts at zero and rises exponentially to a final value of 9V with a time constant of 100us:

>[Relaxation oscillator startup 04](https://easyeda.com/editor#id=d23b3e2d7f2a4628a80d5932346c9dbd)

With symmetrical circuits such as the two transistor astable multivibrator, even this may not be enough to disturb the equilibrium enough to get them oscillating. It may be necessary to introduce some deliberate asymmetry or imbalance into the circuit, for example by making a one base pullup resistor or a timing capacitor a fraction different from the other. Even changes of less than the expected real component tolerance can be enough to tip the circuit into self sustained oscillation with a zero to rated voltage ramped supply start-up.

Sometimes complex circuits - or simple circuits with complex models - may fail to simulate because the simulator cannot find the DC operating point prior to t=0. Such circuits will very often simulate fine if the supply (or supplies) are ramped up from 0. In the same way as slightly imbalancing symmetrical components can help start-up, slightly imbalancing the voltages, delay or rise times of the supply voltage ramps may help start-up more 'difficult' simulations.

There is however, a downside of using the start-up from zero supply ramp. As already stated, at the start of a transient simulation, the voltages across all capacitors and the currents through all inductors in the circuit will have reached their DC steady state values prior to the simulation starting at t=0. If the simulation starts with the supply voltages set to zero at t=0 then obviously all the internal voltages and currents must also be zero (except for some small offsets due to the initial levels of any signal sources and sometimes, badly designed sources internal to models that do not collapse to zero with zero supply voltages).

If all the internal voltages and currents are zero at t=0 then it may take much longer than the desired simulation stop time for all the internal nodes to reach their DC steady states.

A simple solution to this is to run the simulation for long enough for everything to have settled but to only plot the results for just long enough before the stop time to show the signals of interest. So, for example a circuit that is driven by a 1kHz source but which takes 95ms to settle could be observed from say, t=98ms to t=100ms by setting the transient analysis to have a maximum timestep of 1us, a stop time of 100ms and a Start time of 98ms, like this:

>**tran 1u 100m 98m**

This solution works very well but, in this example, over 95% of the simulation time is used just to get the circuit to a steady state before any useful results are generated. This is very wasteful of simulation time and for complex simulations such as switch mode power supply (SMPS) simulations - where exactly this situation is likely to arise - can take many minutes of real time.

This is where another technique for setting initial conditions in a circuit can sometimes be useful.

## Setting initial voltages on nets and currents through components

There are occasions where it is required to start a simulation in some predetermined state. For example, a capacitor may be required to start a transient simulation at time t=0, precharged to some given voltage. Similarly the current in an inductor may need to be specified at time t=0. In a larger simulation it may be helpful to precharge the output smoothing capacitor of a power supply to approximately the right voltage to save the time taken for it to be charged up from zero. If the capacitor is at the output of an SMPS then it may be useful to charge the inductor(s) in the SMPS to their average operating current(s) too.

### Using the `.ic` spice directive to set an initial voltage condition on a net

For more information about the .ic spice directive see:

 >[About-spice-analyses-in-EasyEDA](https://easyeda.com/editor#id=85be332efc8f42bebcabd26abbf30438)

Use of the '.ic' spice directive is illustrated in these two examples:

>[Setting initial circuit conditions 01](https://easyeda.com/editor#id=f207a45edfb1439ebfca58e3fcfa5e07)

>[Relaxation oscillator startup 02](https://easyeda.com/editor#id=1130c58d17e346489f96de06da648389)

These next examples show two ways to use append the 'uic' option to a Transient Analysis but for the reasons already given in the description of the 'uic' option in the section on 'IC: Set Initial Conditions' in 'Setting up Analyses', care should be taken in using this option.

>[Relaxation oscillator startup 05](https://easyeda.com/editor#id=e34071c175824efda9a277d154df7c1c)

>[Relaxation oscillator startup 06](https://easyeda.com/editor#id=fb5634b4f6af4492be8a40f83f846324)

### Using a current source to set an initial current through an inductor

The `.ic` spice directive can only be used to set initial voltage conditions on one or more nets. It cannot be used to set an initial current through a component. This example illustrates a simple way to use a current source to set an initial current through a component.

>[Setting initial circuit conditions 02](https://easyeda.com/editor#id=7ccc6e717ecc4c449c0bde14c11f2caa)

### Setting a capacitor voltage using an XSPICE capacitor model

An alternative to using the '.ic': setting the initial voltage across a capacitor using an XSPICE capacitor model in place of the default EasyEDA capacitor.

>[Setting initial circuit conditions 03](https://easyeda.com/editor#id=e3c517e3c0994a8b8a360da7f35a1b44)

### Setting an inductor current using an XSPICE inductor model

An alternative to using a current source in parallel with an inductor: setting the initial current through an inductor using an XSPICE inductor model in place of the default EasyEDA inductor.

>[Setting initial circuit conditions 04](https://easyeda.com/editor#id=350ba7887bce437ba1468a06cbdaca6b)

Some circuits may start up on their own but simply changing a component model may cause it to fail to start-up. Don't be afraid to try these techniques before spending ages trying to find some other obscure cause.

## Using a 1V source to help start-up

This is an advanced technique which has limited application but which in the right circumstances can be very useful.

By placing a 1V voltage source in a schematic, naming it's output as, say, 'unity' and then multiplying using expressions in B Sources by V(unity), it is possible to force all the B sources in the simulation to start from zero during the early DC operating point parts of a transient simulation.

This can sometimes help produce a clean startup from zero internal initial states.

It must be borne in mind however, that as with other techniques that bring a simulation up from zero, any attempt to run an OP, TF or an AC simulation will usually return zero results because all the internal states and in many cases the gains of B sources will have been forced to a zero initial value.

## Replacing ideal and Thevenin voltage sources with band-limited Norton Sources to help start-up

This is technique is very widely applicable since it helps improve the overall convergence of simulations and not just their startup behaviour.

Ideal voltage sources in simulations are capable of producing infinite currents so a load which looks capacitive at any point during the simulation has the potential to cause an instantaneous infinite current flow. This can cause a simulation to go into overflow or to fail to find a valid next step from which to proceed. In either case, the simulation will fail to converge. To prevent this it is good practice to always include some resistance in series with every voltage source, whether that is an independent V, dependent E or H source or a dependent B source configured as a voltage source.

This turns all ideal voltage sources into Thevenin Sources, i.e. voltage sources with a finite source resistance.

Internally, however, the simulator is actually more efficient at calculating the currents and voltages around a Norton Source than a Thevenin source. So, the next step of the process is to convert all the Thevenin sources in a simulation into Norton Sources.

A Norton Source is the exact equivalent circuit of a Thevenin Source. To convert a Thevenin source to the Norton Equivalent source, the voltage source of the Thevenin source is replaced with a current source equal to the short circuit current of the Thevenin source and the series resistance of the Thevenin source is reconnected in parallel with this current source. Both sources than have identical source resistances, open circuit voltages and short circuit currents.

So far these steps of converting ideal voltage sources to Thevenin sources and then to Norton equivalent sources generally increases the simulation speed of most simulations but the final step of limiting the bandwidth of the Norton sources can significantly improve the start-up and convergence of many simulations.

Limiting the bandwidth (or band-limiting) a Norton Source is easy: all that is required is to connect a capacitor in parallel with the source resistance that has already been connected in parallel with the current source. This creates a lowpass filter across the output of the Norton source which reduces the output at high frequencies. This means that even if the source is passing or generating highly non-linear signals that can produce exactly the kind of very fast and even discontinuous signals that spice struggles to deal with in its internal calculations, as the frequency content of these signals and transitions exceeds the lowpass filter cutoff frequency, they are reduced to relatively slower edged (i.e. reduced high-frequency content) signals. Such signals then have finite rise and fall times and so spice no longer struggles to deal with them. They become much more spice friendly continuous signals.

Even better is that if there are several such band-limited sources sprinkled around the circuit (such as the input signal sources) then very often the derivatives of these signals also become continuous. This is also a big help to spice because much of the internal calculation in spice is in estimating not just where a signal is but also making estimates about where it is going and how fast it is getting there.

Some words of warning are needed here though. Replacing voltage and Thevein sources with band-limited Norton sources is a great technique but it requires a high degree of understanding of what is really going on in a simulation circuit.

The statement above about:

"...all that is required is to connect a capacitor in parallel with the source resistance that has already been connected in parallel with the current source. This creates a lowpass filter across the output of the Norton source which reduces the output at high frequencies."

is all very well but it skirts around the question of what should the value of this capacitance actually be? There is no single answer that question because the cutoff frequency required to avoid convergence or start-up problems will vary from one circuit to another and even from one location to another in a circuit. The single biggest factor affecting the value of simply that the cutoff frequency must be much higher than the working frequencies of not the circuit itself but of the devices in it. So for example, an audio amplifier circuit designed for a bandwidth of 20kHz may use an opamp that is operated with a closed loop bandwidth that is 200kHz but which internally may have a gain bandwidth of 2MHz or even 20MHz.

In practice, setting the cutoff frequency with an RC time constant of 1ps (1e-12s) i.e. approximately 160GHz should be safe for most 'ordinary' simulations of amplifiers, linear and switch mode power supply circuits but for high frequency and RF circuits the band-limiting must be increased accordingly.

The value of the resistor in this parallel RC circuit can be also be very tricky to decide. For many lightly loaded voltage sources, a value of 1 Ω is OK and simplifies the calculation of the parallel capacitance to 1pF. In some sources, however, it may be necessary to use a higher (or lower value) of parallel resistance. This in turn will require the use of a proportionately smaller (or larger) capacitance for the same cutoff frequency.

This band-limiting technique should generally not be applied around any existing current sources in a simulation circuit. Placing an RC circuit in parallel with a pure current source may do more damage to the operation of the circuit by reducing the in-band source impedance of the current source than the band-limiting avoids!

Although not an example of a start-up or initialisation problem, the Ideal and Thevenin to Norton Source conversion is demonstrated in steps (i), (ii) and (iii) of this simulation:

>[Parameters, expressions, functions and B Sources](https://easyeda.com/editor#id=3fc42cc7866048fcaa8ca63d0ad2a4cf)

## Using the 'OFF' option to help start-up

Some components, such as switches, bjts, jfets, MOSFETs and MESFETs have an 'OFF' option to specify the device to be in an initial OFF state.

Switches also have an 'ON' option to specify the device to be in an initial ON state.

This option can be very useful to ensure that for example, one side of a two transistor bistable or monostable circuit or an astable mutlivibrator is off, so avoiding the situation described above where both transistors are on in the initial state. Whilst this does not in itself guarantee that the circuit will start up from t=0 but it may simplify any other measures that have to be taken to ensure it does.

These states are simply invoked by appending the keyword OFF (or, for switches only, ON) after the device name. This can be done either by directly editing the name in place in the schematic or via the right hand panel Properties dialogue. For example, to set a switch with the name MYSWITCH to be initially ON the name should be edited to:

>**MYSWITCH ON**

Similarly, to set a bjt with the name 2N2222 to be initially OFF the name should be edited to:

>**2N2222 OFF**

# Expressions

Expressions can be used to define component values and to help configure Voltage and Current Sources.

## Operators

In expressions, parentheses are evaluated before the other operators. The operators are evaluated following a list of precedence as shown in the table below. For equal precedence binary operators, evaluation goes left to right. Functions operate on real values only!

Operator

Alias

Precedence

Description

-

1

unary negate (see Note 1 below)

!

1

unary not

**

^

2

power (but see also the pow(x,a), pwr(x,a) and pwrs(x,a) functions)

*

3

multiply

/

3

divide

%

3

modulo (does not work in B Source expressions)

\

3

integer divide (does not work in B Source expressions)

+

4

add

-

4

subtract

==

5

equality

!=

<>

5

non-equal

<=

5

less or equal

>=

5

greater or equal

<

5

less than

>

5

greater than

&&

6

boolean and

||

7

boolean or

c?x:y

8

ternary operator (See also the if(x,y,z) and ifx(x,y,z) functions)

|**Operator**|**Alias        **|**Precedence**|**Description**|

|---                |---                |---                        |---                        |

|-                |                |1                        |unary negate (see Note 1 below)|

|!                |                |1                        |unary not        |

|**                |^                |2                        |power (but see also the pow(x,a), pwr(x,a) and pwrs(x,a) functions)|

|*                |                |3                        |multiply        |

|/                |                |3                        |divide        |

|%                |                |3                        |modulo (does not work in B Source expressions)|

|\                |                |3                        |integer divide (does not work in B Source expressions)|

|+                |                |4                        |add                |

|-                |                |4                        |subtract        |

|==                |                |5                        |equality        |

|!=                |<>                |5                        |non-equal        |

|<=                |                |5                        |less or equal        |

|>=                |                |5                        |greater or equal        |

|<                |                |5                        |less than                        |

|>                |                |5                        |greater than                |

|&&                |                |6                        |boolean and                |

|&#124;&#124;        |                |7                        |boolean or                |

|c?x:y        |                |8                        |ternary operator (See also the if(x,y,z) and ifx(x,y,z) functions)        |

>***Note 1***

>*At the time of writing (141021), the ngspice implementation of the unary negate or subtract symbol works as expected when used in this type of expression:*

>>***.param myparameter = {A-B}***

>*but may produce unexpected results when used in an expression for a B Source (or in a .func statement) like this:*

>>***V=5*(1-exp(-time/1m))***

>*This expression must be written instead as:*

>>***V=5*(1-exp(-1*time/1m))***

*This is a feature of ngspice. It is hoped that this anomaly will be corrected at some point in the future and that this will feed into later revisions of EasyEDA.*

The number zero is used to represent boolean False. Any other number represents boolean True. The result of logical operators is 1 or 0.

Some examples of logical operators used to defined value of voltage sources:

>**V1or 1 0 {1 | | 0}**

>**V2and 2 0 {1 && 0}**

>**V3not 3 0 { ! 1}**

>**V4mod 4 0 {5 % 3}**

>**V5div 5 0 {5 \ 3}**

>**V6not 6 0 { ! 0}**

**Note that when used directly in component and source value fields, expressions MUST be on a single line. When used like this, expressions cannot be wrapped over more than one line.**

## Using Expressions to define component values

The -3dB frequency, fc, of a first order RC lowpass filter is given by:

>fc = 1/(2*pi*R*C)

Exactly the same expression applies to a first order RC highpass filter.

If fc is specified as 10kHz and R is chosen as 1k then:

>C = 1/(2*pi*1k*10k)

Suppose the high pass filter output is required to be attenuated by a factor, A.

The total value of R for the highpass filter is still 1k but it must be split into a lower resistor with a value given by:

>Rlower = (Rupper+Rlower)*1/A

whilst the upper value is given by:

>Rupper = (Rupper+Rlower)*(1-1/A)

If we choose A=3 then for the chosen value of R=1k

>Rlower = 1k*1/3

and:

>Rupper = 1k*2/3

Simply by entering the right hand side of these expressions into the component values fields, enclosed in curly brackets like this:

>`{expression}`

the value of those components will be defined directly by those expressions, as illustrated in Rupper and Rlower in this example.

## Using Expressions to configure voltage and current sources

In this example, PULSE source V1 is configured to generate a signal with a 20us rise and fall time, a frequency of 5kHz and exactly equal high and low times: in other words, a slow edged squarewave of 200us period and a 50% duty cycle.

Because a PULSE source is defined in terms of Trise and Ton, it can be helpful to think of the time interval from the start of the rising (leading) edge to the start of the falling (trailing) edge as the 'pulse width', Twidth:

>Twidth = Trise+Ton

It is then a simple matter to define the PULSE source in terms of Trise and Twidth without having to manually calculate a value for Ton because:

>Ton = Twidth-Trise

From this we can also see that if the 'duty cycle' is defined as:

>D = Twidth/Tperiod

then for a given D:

>Ton = D*Tperiod - Trise

Lastly, it is sometimes convenient to define the period of a PULSE source in terms of a frequency:

>Frequency = 1/Tperiod

To use an expression in a source, simply enter it in place of the value you wish to calculate and enclose it in curly brackets like this:

>`{expression}`

The use of expressions is illustrated in the following example:

>[Using expressions 01](https://easyeda.com/editor#id=b0b2d50656f4431dad77542e47335a92)

# Parameters

Usually, the values of components are specified directly in the component's value field. There are, however, occasions where it is desirable to be able to set or change the value of several components at once without having to edit each individual component value.

The simple resistor attenuator circuit used to illustrate several of the early examples has one resistor of 1k and two of 2k. Instead of entering the value 1k into one resistor resistor 2k into each of the others, it is possible to set up two variables to represent these values.

To create two variables, R1val=1k and R2val=2k, a  `.param` statement is placed into the schematic and turned into a spice directive (by doing: **Text Attributes > Text type = spice**):

>`.param R1val=1k R2val=2k`

The parameters are then used to define the values of the components in their value fields.

By placing more than one .param statement in a schematic and doing:

>**Text Attributes > Text type = comment**

And

>**Text Attributes > Text type = spice**

It is possible to switch sets of values without having to edit individual components every time.

Using .param statements therefore makes it possible to:

* change the value of several components a single edit;

* define parameters in terms of other parameters;

* define parameters in terms of functions of other parameters.

Note that it is also possible to have several .param statements active in a simulation at the same time but to avoid the conflict caused by duplicate definitions, the parameter identifier names in each set must be unique.

The syntax of .param statements is:

~~~

`.param <param_name1>=<value1> <param_name2>=<value2> ... <param_nameN>=<valueN>`

~~~

'.param' statements can wrap over more than one line by using the '+' continuation character:

~~~

.param

+ <param_name>=<value1>

+ <param_name2>=<value2>

+ ...

+ ...

+ ...

+ <param_nameN>=<valueN>

~~~

Parameters can be numbers, other defined parameters or expressions made up from any combination of numbers and defined parameters.

Parameter identifier names must begin with an alphabetic character. The other characters must be either alphabetic, a number, or;

~~~

! # $ % > [ ] _

~~~

as special characters.

**Note that when used in .param statements, expressions can wrap over more than one line by using the '+' continuation character:**

~~~

.param

+ <param_name>=<value1>

+ <param_name2>=<value2>

+ <param_name3>=<{expression1}>

+ <param_name4>=<{part of expression2 + continuation of expression2}>

+ ...

+ <param_nameN>=<valueN>

~~~

Care must be taken in choosing the line break points to clearly distinguish the use of the '+' character as a continuation character from any mathematical use of the '+' character as an addition operator in an expression.

For example:

~~~

.param x=3 y=4

+ hypotenuse={sqrt(x^2+

+ y^2)}

~~~

and:

~~~

.param x=3 y=4

+ hypotenuse={sqrt(x^2 +

+y^2)}

~~~

are valid wrappings of expression in a .param statement which will give the expected results, whereas:

~~~

.param x=3 y=4

+ hypotenuse={sqrt(x^2

+ y^2)}

~~~

or:

~~~

.param x=3 y=4

+ hypotenuse={sqrt(x^2+

y^2)}

~~~

or:

~~~

.param x=3 y=4

+ hypotenuse={sqrt(x^2

+y^2)}

~~~

may give unexpected results or may fail with errors.

* Note that the variables TIME, TEMPER or TEMP and HERTZ are NOT valid identifier names because in ngspice, they are reserved names.

Note that to use a parameter in a component value field, it must be enclosed in curly brackets:

>{...}

A parameter should also be enclosed in curly brackets if it is being used to define the value of another parameter, as in the example here of:

>`R3val={R2val}`

Although not shown here, the use of curly brackets to enclose expressions containing parameters which are then used to define other parameters is mandatory so, even though the use of curly brackets in the example shown above is not mandatory, it is good practice to always enclose in curly brackets any parameter or expression used in a parameter definition.

* Note, however, that parameters in expressions used in B Sources must should not be enclosed in curly brackets.

The basic use of parameters is illustrated below:

>[Using parameters 01](https://easyeda.com/editor#id=85fef57e59484f7480a7d2a338781cf5)

## Using parameters in expressions

Expressions and parameters can be combined to simplify and automate the calculation of component and source configuration values, as illustrated in the following example:

>[Using parameters in expressions 01](https://easyeda.com/editor#id=79c4d38cf47e440390bf244cbfc488b6)

# Functions

The sections on expressions and parameters shows how component and source values can be defined using arithmetic equations. The examples used to illustrate this used only simple linear expressions. This section introduces the concept of functions.

Functions hugely expand the power of parameters and expressions by allowing the creation of expressions including non-linear functions of other parameters.

## Predefined functions

EasyEDA has a number of pre-defined functions. Many of them are immediately available to be used in expressions because they are built-in to ngspice or they are automatically added in to the spice netlist by EasyEDA at the time of first saving a schematic.

Some are not yet automatically added in to the netlist so their definitions must be pasted in manually before they can be used. These function definitions are clearly indicated in the examples illustrating each function.

These functions will be appended to the list of those automatically added to the netlist soon.

All the currently available pre-defined functions are listed, together with illustrative examples, in the table below.

Note that all the functions in this list can be used in any context in EasyEDA: in the value fields and in expressions for component values (E), Independent Sources (I) and for B Sources (B).

**Table of functions**

**Function**

**Description**

**ngspice native or EasyEDA special**

**Where useable**

[abs(x)](https://easyeda.com/editor#id=c2fa14e74a10468db29ece41787fa969)

Absolute value of x

ngspice

E, I, B

[acos(x)](https://easyeda.com/editor#id=9b98b7cda0b74c34a07788880c75cb2f)

Arc cosine of x. Fails to converge for x < -1 and x > +1. Use invcos(x) instead.

ngspice

E, I, B

[acosh(x)](https://easyeda.com/editor#id=2adb691d54db43f9aecf91d791812cfb)

Real part of the arc hyperbolic cosine of x, e.g., acosh(.5) returns 0, not 1.0472i

EasyEDA

E, I, B

[arctan(x)](https://easyeda.com/editor#id=c58cf1f82e88443d808a3e83692a4ad1)

Alternate syntax to atan(x)

ngspice

E, I, B

[asin(x)](https://easyeda.com/editor#id=5d3ae3825f494fba8f880711049d97ac)

Arc sine of x. Fails to converge for x < -1 and x > +1. Use invsin(x) instead.

ngspice

E, I, B

[asinh(x)](https://easyeda.com/editor#id=1e0dde02b65f4890bc9f4c3e231997c0)

Arc hyperbolic sine

EasyEDA

E, I, B

[atan(x)](https://easyeda.com/editor#id=c58cf1f82e88443d808a3e83692a4ad1)

Arc tangent of x

ngspice

E, I, B

[atan2(y,x)](https://easyeda.com/editor#id=9621b410588e4dc597b290f5316a6153)

4 quadrant arc tangent of x/y (tan^-1(x/y))

EasyEDA

E, I, B

[atanh(x)](https://easyeda.com/editor#id=3279efb26ab54856ae800f6a1db8f467)

Arc hyperbolic tangent. (Limited output swing to avoid numerical under/overflow failure.)

EasyEDA

E, I, B

[buf(x)](https://easyeda.com/editor#id=68191c2534334ca6912029e4ff7c7ba2)

Returns 1 if x > 0.5, else 0

EasyEDA

E, I, B

[ceil(x)](https://easyeda.com/editor#id=697bbf5a947a47ec901ebf6163dcfd1b)

Integer equal or greater than x

ngspice

E, I, B

[cos(x)](https://easyeda.com/editor#id=84159a53154846babeb8df3278b8ed10)

Cosine of x

ngspice

E, I, B

[cosh(x)](https://easyeda.com/editor#id=df42925ac14f4fedbb0eb97b8915f15e)

Hyperbolic cosine of x

ngspice

E, I, B

[exp(x)](https://easyeda.com/editor#id=687d1e8e385f4374995574e01e865d80)

e to the power of x

ngspice

E, I, B

[floor(x)](https://easyeda.com/editor#id=050a2f94c41242eaad7542f2159011bb)

Integer equal to or less than x

ngspice

E, I, B

[if(x,y,z)](https://easyeda.com/editor#id=050a2f94c41242eaad7542f2159011bb)

IF x > 0.5, THEN y ELSE z

EasyEDA

E, I, B

[ifx(x,y,z)](https://easyeda.com/editor#id=ae3af3ea5a1e41dcb762f1d4a83f02f0)

IF x, THEN y ELSE z

EasyEDA

E, I, B

[int(x)](https://easyeda.com/editor#id=a2c0542045544fbe806742000a12bf7c)

Convert x to integer

EasyEDA

E, I, B

[inv(x)](https://easyeda.com/editor#id=37c60e3a476d49d385f23d35ed36cf64)

Returns 0 if x > 0.5, else 1

EasyEDA

E, I, B

[invcos(x)](https://easyeda.com/editor#id=69b8758b71ea43c49445185e5f48cb68)

Real part of the arc cosine of x, e.g., acos(-5) returns 3.14159, not 3.14159+2.29243i

EasyEDA

E, I, B

[invsin(x)](https://easyeda.com/editor#id=1c1d83fe4e45414b8500ab6515dc41af)

Real part of the arc sine of x, asin(-5) returns -1.57080, not -1.57080+2.29243i

EasyEDA

E, I, B

[invtan(x)](https://easyeda.com/editor#id=77c6c5cb9a294f0eb8dc367afa5ab791)

Alternate syntax to atan(x)

EasyEDA

E, I, B

[limit(x, L, U)](https://easyeda.com/editor#id=9ac593619e6d41c7a7cfc40d343917bf)

Value of x, bounded by L and U

EasyEDA

E, I, B

[ln(x)](https://easyeda.com/editor#id=586c3b85a0ae481c8b83f724efb986aa)

Natural logarithm of x. Fails with errors for negative x. Use log(x) instead.

ngspice

E, I, B

[log(x)](https://easyeda.com/editor#id=b554280b130d482983b1e94a640bee04)

Natural logarithm of x. Generates a real valued output for all x, limited to a minimum of approximately -230.5 for x <= 1e-100.

EasyEDA

E, I, B

[log10(x)](https://easyeda.com/editor#id=994653179e914155b3fd64eb97a11b11)

Base 10 logarithm. Generates a real valued output for all x, limited to a minimum of -100 for x <= 1e-100.

EasyEDA

E, I, B

[max(x,y)](https://easyeda.com/editor#id=bd314f6c79f442eb9424d9a94d2ce00a)

The greater of x or y

ngspice

E, I, B

[min(x,y)](https://easyeda.com/editor#id=bbc0196c6fd14cccaffdbf8b73302e8b)

The smaller of x or y

ngspice

E, I, B

[pow(x,a)](https://easyeda.com/editor#id=b867c4bd3c7f4552bb607c672884a9df)

Real part of x raised to the power of a. Zero for negative x and fractional a

EasyEDA

E, I, B

[pwr(x,a)](https://easyeda.com/editor#id=b867c4bd3c7f4552bb607c672884a9df)

The absolute value of x raised to the power of a

EasyEDA

E, I, B

[pwrs(x,a)](https://easyeda.com/editor#id=b867c4bd3c7f4552bb607c672884a9df)

pwr(x) multiplied by the sign of x

EasyEDA

E, I, B

[sgn(x)](https://easyeda.com/editor#id=12b60f93af2d412bbf3a404cd8a959d5)

Sign of x. Returns -1 for x < 0, 0 for x == 0 (where == means 'exactly equal to') and 1 for x > 0

ngspice

E, I, B

[sin(x)](https://easyeda.com/editor#id=9103342d6acd4c7093eefa2d3c824b64)

Sine of x

ngspice

E, I, B

[sinh(x)](https://easyeda.com/editor#id=172f7f10124a4d23944e4ca0eb853113)

Hyperbolic sine of x

ngspice

E, I, B

[softlim(ip, lo, hi, sharp)](https://easyeda.com/editor#id=2d2c47a6bdf24d469554eff272f1bbfa)

Value of ip, bounded by lo and hi with the sharpness of the transition between linear and limited regions defined by 'sharp'.

EasyEDA

E, I, B

[sqr(x)](https://easyeda.com/editor#id=39de13fbc51341e8b7025fc30552194f)

Square of x

EasyEDA

E, I, B

[sqrt(x)](https://easyeda.com/editor#id=fa83a1fc17454ecf8e3f87ccb5c3a71d)

Real part of the square root of x. Zero for negative x

EasyEDA

E, I, B

[stp(x)](https://easyeda.com/editor#id=7671e59969c7487eb3a2b541b555e275)

Alternate syntax for u(x)

EasyEDA

E, I, B

[tan(x)](https://easyeda.com/editor#id=d3ade2ee327443a9b816f570a95cd111)

Tangent of x

ngspice

E, I, B

[tanh(x)](https://easyeda.com/editor#id=01e29da38bc84fd4b8eb9eef51f1bb1b)

Hyperbolic tangent of x

ngspice

E, I, B

[u(x)](https://easyeda.com/editor#id=7671e59969c7487eb3a2b541b555e275)

Unit step, i.e., 1 if x > 0., else 0

EasyEDA

E, I, B

[u2(x)](https://easyeda.com/editor#id=c2dc39542f734feb9a6090218e6d4308)

Returns 1 for x >= to 1, x for x between 0 and 1, 0 for x <= 0.

EasyEDA

E, I, B

[uramp(x)](https://easyeda.com/editor#id=2bfb6b65ff10403bb3fb46017a4485f7)

x if x > 0, else 0

EasyEDA

E, I, B

|**Function**|**Description**|**ngspice native or EasyEDA special**|**Where useable**|

|---                |---                |---                        |---                        |

|[abs(x)](https://easyeda.com/editor#id=c2fa14e74a10468db29ece41787fa969)         |Absolute value of x                                                                         |ngspice |E, I, B |

|[acos(x)](https://easyeda.com/editor#id=9b98b7cda0b74c34a07788880c75cb2f)         |Arc cosine of x. Fails to converge for x < -1 and x > +1. Use invcos(x) instead.         |ngspice |E, I, B |

|[acosh(x)](https://easyeda.com/editor#id=2adb691d54db43f9aecf91d791812cfb)         |Real part of the arc hyperbolic cosine of x, e.g., acosh(.5) returns 0, not 1.0472i         |EasyEDA |E, I, B |

|[arctan(x)](https://easyeda.com/editor#id=c58cf1f82e88443d808a3e83692a4ad1)        |Alternate syntax to atan(x)        |ngspice  |E, I, B |

|[asin(x)](https://easyeda.com/editor#id=5d3ae3825f494fba8f880711049d97ac)        |Arc sine of x. Fails to converge for x < -1 and x > +1. Use invsin(x) instead.        |ngspice |E, I, B |

|[asinh(x)](https://easyeda.com/editor#id=1e0dde02b65f4890bc9f4c3e231997c0)        |Arc hyperbolic sine        |EasyEDA |E, I, B |

|[atan(x)](https://easyeda.com/editor#id=c58cf1f82e88443d808a3e83692a4ad1)        |Arc tangent of x        |ngspice |E, I, B |

|[atan2(y,x)](https://easyeda.com/editor#id=9621b410588e4dc597b290f5316a6153)        |4 quadrant arc tangent of x/y (tan^-1(x/y))        |EasyEDA |E, I, B |

|[atanh(x)](https://easyeda.com/editor#id=3279efb26ab54856ae800f6a1db8f467)        |Arc hyperbolic tangent. (Limited output swing to avoid numerical under/overflow failure.)        |EasyEDA |E, I, B |

|[buf(x)](https://easyeda.com/editor#id=68191c2534334ca6912029e4ff7c7ba2)        |Returns 1 if x > 0.5, else 0        |EasyEDA |E, I, B |

|[ceil(x)](https://easyeda.com/editor#id=697bbf5a947a47ec901ebf6163dcfd1b)        |Integer equal or greater than x        |ngspice |E, I, B |

|[cos(x)](https://easyeda.com/editor#id=84159a53154846babeb8df3278b8ed10)        |Cosine of x        |ngspice |E, I, B |

|[cosh(x)](https://easyeda.com/editor#id=df42925ac14f4fedbb0eb97b8915f15e)        |Hyperbolic cosine of x        |ngspice |E, I, B |

|[exp(x)](https://easyeda.com/editor#id=687d1e8e385f4374995574e01e865d80)         |e to the power of x        |ngspice |E, I, B |

|[floor(x)](https://easyeda.com/editor#id=050a2f94c41242eaad7542f2159011bb)        |Integer equal to or less than x        |ngspice |E, I, B |

|[if(x,y,z)](https://easyeda.com/editor#id=050a2f94c41242eaad7542f2159011bb)        |IF x > 0.5, THEN y ELSE z        |EasyEDA |E, I, B |

|[ifx(x,y,z)](https://easyeda.com/editor#id=ae3af3ea5a1e41dcb762f1d4a83f02f0)        |IF x, THEN y ELSE z        |EasyEDA |E, I, B |

|[int(x)](https://easyeda.com/editor#id=a2c0542045544fbe806742000a12bf7c)        |Convert x to integer        |EasyEDA |E, I, B |

|[inv(x)](https://easyeda.com/editor#id=37c60e3a476d49d385f23d35ed36cf64)        |Returns 0 if x > 0.5, else 1        |EasyEDA |E, I, B |

|[invcos(x)](https://easyeda.com/editor#id=69b8758b71ea43c49445185e5f48cb68)        |Real part of the arc cosine of x, e.g., acos(-5) returns 3.14159, not 3.14159+2.29243i        |EasyEDA |E, I, B |

|[invsin(x)](https://easyeda.com/editor#id=1c1d83fe4e45414b8500ab6515dc41af)        |Real part of the arc sine of x, asin(-5) returns -1.57080, not -1.57080+2.29243i        |EasyEDA |E, I, B |

|[invtan(x)](https://easyeda.com/editor#id=77c6c5cb9a294f0eb8dc367afa5ab791)        |Alternate syntax to atan(x)        |EasyEDA |E, I, B |

|[limit(x, L, U)](https://easyeda.com/editor#id=9ac593619e6d41c7a7cfc40d343917bf)        |Value of x, bounded by L and U        |EasyEDA |E, I, B |

|[ln(x)](https://easyeda.com/editor#id=586c3b85a0ae481c8b83f724efb986aa)        |Natural logarithm of x. Fails with errors for negative x. Use log(x) instead.        |ngspice |E, I, B |

|[log(x)](https://easyeda.com/editor#id=b554280b130d482983b1e94a640bee04)        |Natural logarithm of x. Generates a real valued output for all x, limited to a minimum of approximately -230.5 for x <= 1e-100.        |EasyEDA |E, I, B |

|[log10(x)](https://easyeda.com/editor#id=994653179e914155b3fd64eb97a11b11)        |Base 10 logarithm. Generates a real valued output for all x, limited to a minimum of -100 for x <= 1e-100.        |EasyEDA |E, I, B |

|[max(x,y)](https://easyeda.com/editor#id=bd314f6c79f442eb9424d9a94d2ce00a)        |The greater of x or y        |ngspice |E, I, B |

|[min(x,y)](https://easyeda.com/editor#id=bbc0196c6fd14cccaffdbf8b73302e8b)        |The smaller of x or y        |ngspice |E, I, B |

|[pow(x,a)](https://easyeda.com/editor#id=b867c4bd3c7f4552bb607c672884a9df)        |Real part of x raised to the power of a. Zero for negative x and fractional a        |EasyEDA |E, I, B |

|[pwr(x,a)](https://easyeda.com/editor#id=b867c4bd3c7f4552bb607c672884a9df)        |The absolute value of x raised to the power of a        |EasyEDA |E, I, B |

|[pwrs(x,a)](https://easyeda.com/editor#id=b867c4bd3c7f4552bb607c672884a9df)        |pwr(x) multiplied by the sign of x        |EasyEDA |E, I, B |

|[sgn(x)](https://easyeda.com/editor#id=12b60f93af2d412bbf3a404cd8a959d5)        |Sign of x. Returns -1 for x < 0, 0 for x == 0 (where == means 'exactly equal to') and 1 for x > 0        |ngspice |E, I, B |

|[sin(x)](https://easyeda.com/editor#id=9103342d6acd4c7093eefa2d3c824b64)        |Sine of x        |ngspice |E, I, B |

|[sinh(x)](https://easyeda.com/editor#id=172f7f10124a4d23944e4ca0eb853113)        |Hyperbolic sine of x        |ngspice |E, I, B |

|[softlim(ip, lo, hi, sharp)](https://easyeda.com/editor#id=2d2c47a6bdf24d469554eff272f1bbfa)        |Value of ip, bounded by lo and hi with the sharpness of the transition between linear and limited regions defined by 'sharp'.        |EasyEDA |E, I, B |

|[sqr(x)](https://easyeda.com/editor#id=39de13fbc51341e8b7025fc30552194f)        |Square of x        |EasyEDA |E, I, B |

|[sqrt(x)](https://easyeda.com/editor#id=fa83a1fc17454ecf8e3f87ccb5c3a71d)        |Real part of the square root of x. Zero for negative x        |EasyEDA |E, I, B |

|[stp(x)](https://easyeda.com/editor#id=7671e59969c7487eb3a2b541b555e275)        |Alternate syntax for u(x)        |EasyEDA |E, I, B |

|[tan(x)](https://easyeda.com/editor#id=d3ade2ee327443a9b816f570a95cd111)        |Tangent of x        |ngspice |E, I, B |

|[tanh(x)](https://easyeda.com/editor#id=01e29da38bc84fd4b8eb9eef51f1bb1b)        |Hyperbolic tangent of x        |ngspice |E, I, B |

|[u(x)](https://easyeda.com/editor#id=7671e59969c7487eb3a2b541b555e275)        |Unit step, i.e., 1 if x > 0., else 0        |EasyEDA |E, I, B |

## User defined functions

There may be occasions where a function is required that maybe has to be used in several places in a schematic or it is useful in several different schematics. To save having to copy and paste a complicated expression as a block of text each time it is needed, the .func statement makes it is possible to create a user defined function.

The syntax of the .func statement is very simple:

>`.func myfunctionname(a,b,c, ...n) {expression of functions of a, b, c ... n}`

For example:

>`.func hypotenuse(x,y) {sqrt(x^2+y^2)}`

defines a function that calculates the length of the hypotenuse of a right angle triangle with sides length x and y.

Once a function has been defined in a schematic in a project in this way it can be used anywhere in any schematic in that project, i.e. it does not have to be defined separately in every sheet in which it is used in a project. It does, however, have to be defined in a sheet in every project in which it is to be used but, if it's a really useful function, let us know and maybe we'll add it to the growing list of pre-defined functions!

To use the function all that is then required is to paste `hypotenuse(x,y)` into wherever it is needed and to substitute the 'x' and 'y' with the required variables. So, for example to use the function in a parametric expression:

>`.param a=3 b=4 hypot=hypotenuse(a,b)` 

or in a current output B Source driven by two voltages, V(oneside) and V(otherside):

>`I=hypotenuse(V(oneside), V(otherside))` 

There are many examples of functions defined by the .func statement in the simulations linked to in the table above and in all EasyEDA spice netlists for the automatically appended predefined functions.

**Note that when used in .func statements, expressions can wrap over more than one line by using the '+' continuation character.**

There are several examples of this in the simulations linked to in the table above and in all EasyEDA spice netlists for the automatically appended predefined functions. For example:

~~~

.func POW(x,a)

+ {(((a-(int(a)))==0)||(sgn(x)>=0))*( max(exp(ln(uramp(x))*a),0) +

+ (2*(0.5-ABS((int(a))-2*int(a/2))))*max(exp(ln(uramp(-1*x))*a),0) )}

~~~

can be found appended to every EasyEDA spice netlist.

# B sources

B sources are one of the most powerful components in EasyEDA. They are available as a BV voltage source and as BI current source (although in fact at the spice netlist level they are the same device just defined to have a voltage or a current output).

The function of every B source is defined by an equation.

The left hand side of the equation defines whether the output of the source is a voltage or a current.

The right hand side is an expression made up from numbers, the basic arithmetic operators and functions not only of parameters but, crucially, of dynamic voltages and currents from within the circuit being simulated. In other words, B sources can perform a range of functions in simulations that is limited only by the imagination of the simulation designer.

The syntax of the equations to define a BV source in EasyEDA is very simple:

>**V=expression**

For example:

>**V=3*V(a,b)**

defines a BV source that generates an output voltage equal to 3 times the difference between the voltage on the 'a' net (V(a)) and the voltage on the 'b' net (V(b)).

>**V=scale*uramp(V(a,b))/ABS(I(Vimon))**

defines a BV source that generates an output voltage equal to the parameter, scale, multiplied by the positive difference between the voltage on the 'a' net (V(a)) and the voltage on the 'b' net (V(b)), divided by the absolute value of the current through the 0V source Vimon (I(Vimon)).

>**V=Vswing*tanh(V(a,b)*Avol)**

defines a differential gain block with an small signal gain of Avol and an output voltage swing which is limited with a tanh function to +/-Vswing.

The syntax of the equations to define a BI source in EasyEDA is basically the same as for BV sources except that **V** for voltage is replaced by **I** for current:

>**I=expression**

>**I=V(a)*I(Vimon)**

defines a BI source that generates an output current equal to the voltage on the 'a' net (V(a)) multiplied by the current through the 0V source Vimon (I(Vimon)).

>**I=LIMIT(V(a), 3, minval^2)**

defines a BI source that generates an output current equal to the voltage on the 'a' net (V(a)) but clamped to the value of 3 and the square of the value of the minval parameter for all values of V(a) outside the range defined by 3 and minval^2.

>**I=V(a,b)/Rval**

when the '-' and '+' terminals of the B source are named 'a' and 'b' respectively then this expression defines a resistor of value Rval.

Note that curly brackets are not used in expressions for B Sources.

There are several examples of the uses of B Sources in the following simulations.

>[B Sources 01](https://easyeda.com/editor#id=cabd3b5fe71a44e1984169405eb4881b)

>[limit(x, L, U)](https://easyeda.com/editor#id=9ac593619e6d41c7a7cfc40d343917bf)

>[Parameters, expressions, functions and B Sources](https://easyeda.com/editor#id=3fc42cc7866048fcaa8ca63d0ad2a4cf)

**Note that when entered directly in a B Source value field in a schematic, expressions MUST be on a single line. When used like this, they cannot be wrapped over more than one line.**

Expressions entered into a netlist, however, such as inside a .subckt model definition, can wrap over more than one line by using the '+' continuation character. Several examples of this can be found by inspecting the netlists of circuits using some of the EasyEDA .subckt models. For example in the netlist of the opamp5pEE Parameterised 5 pin opamp model there are these B sources:

~~~

Bipbias1 inp isum I=(ibias+ios)*V(supply_ok) +

+ ( uramp(V(inn)-(V(vp)+inmax)) - uramp(-V(inn)+(V(vn)-inmin)) )/Rser

~~~

and:

~~~

Bstg1 0 stage1 I=Islew*tanh(V(indiff)*Kg)

+ - ( uramp(V(stage1)-(V(vp)-outhi)) - uramp(-V(stage1)+(V(vn)+outlo)) )/Rser

+ - sel*( uramp(V(stage1)-(V(out)+oooclmphi)) - uramp(-V(stage1)+(V(out)-oooclmplo)) )/Rser

~~~

and in the opamp_ANF01 .subckt found elsewhere in this document, there is another example:

~~~

B1 out 0 + V=(TANH((V(inp)-V(inn))*{Avol}*2/(V(vcc)-V(vee)))*(V(vcc)-V(vee)) + +(V(vcc)+V(vee)))/2

~~~

# Device models

In order to simulate the behaviour of the individual components, they have to be described mathematically. The underlying equations that describe the behaviour of a component are written into the simulator program (sometimes they can be added by the user).

The equations that describe basic components such as resistors (I = V/R), capacitors (I = C*dV/dt) and inductors (V = L*di/dt) may be reasonably straightforward. The equations that describe diodes, bipolar (bjt) and a variety of field effect (jfet) and MOS transistors become increasingly complex, sometimes with several equations describing the behaviour of different aspects of device performance in different regions of operation.

Because these sets of equations are very much based on the semiconductor physics of devices and the manufacturing processes used to fabricate them, for some families of devices, such as MOSFETs, different sets of equations may be used to describe devices in the same family. The different sets of equations may be used because the manufacturer wishes to describe the operation of their devices to a greater or lesser degree of accuracy.

Although the equations themselves are hidden deep in the source code for a simulator, in general the coefficients of the sets of equations are collected together in the form of a list. Individual devices of any particular device family can then be described by a list of coefficients.

This list of coefficients is called a **model**.

The individual coefficients in a model are called the **model parameters**.

A device model written in this way is called a **.model** statement.

Some devices such as Thyristors, opamps, linear regulators and switch mode supply chips are made up from a number of other devices connected together to form subcircuits.

A spice netlist of a device defined by a subcircuit is also referred to as a **model**.

A device model written in this way is called a **.subckt**.

Subcircuit models may themselves contain .model statements.

Subcircuits can also contain parameters and can also have parameters passed to them to change their characteristics for example to tailor them to a particular device variant.

## Why are there different models for the same device?

Because each family of devices (resistors, diodes, bjts, jfets, MOSFETs etc.) is described by one or more sets of equations, each family has one or more models available for it.

One reason there are different models available for devices in the same family is because manufacturers give device models away for free. Therefore they do not want to spend any more time on developing device models than they need to. Basically, the more complex a model is, the more time the manufacturer has to spend on making measurements in order to derive the model parameters. Therefore if one manufacturer feels that a device can be adequately described by a simple model then they will use that rather than a more accurate but more complex and so more expensive one that may be available from a different manufacturer.

Another reason there may be differences between models of the same device is that there may be slight differences in the semiconductor fabrication processes of different manufacturers.

In the same way ththeyat there may be more than one .model available for a device. there may be different .subckt defined models available.

There may be differences between .subckt models because there are implementation differences in the device models and/or the physical devices from different manufacturers. For example there are slight differences in internal timings and even a subtle difference in the internal circuitry of the oscillator section of the UC384x family of SMPS controllers between the various different manufacturers.

Sometimes, there are differences in the models just to get around the copyright protection. Some differences are to optimise the model for a particular simulator and some differences are simply down to the preferences of the model writer.

## .model statements

In the spice netlist of a circuit, the user can see the models listed in .model statements. When a schematic is saved, these .model statements are pulled in to the netlist by EasyEDA recognising the symbols and their associated device names given in the schematic. Each model may either be pulled in from a library or - for devices that are not in the EasyEDA libraries - by downloading a model from a manufacturer's website and then manually pasting it directly into the schematic (the process of doing this will be described later).

### Ngspice model types

To help identify model types and in particular if they are for N or P type devices, the following table of model types may be helpful.

**Code**

**Model Type**

R

Semiconductor resistor model

C

Semiconductor capacitor model

L

Inductor model

SW

Voltage controlled switch

CSW

Current controlled switch

URC

Uniform distributed RC model

LTRA

Lossy transmission line model

D

Diode model

NPN

NPN BJT model

PNP

PNP BJT model

NJF

N-channel JFET model

PJF

P-channel JFET model

NMOS

N-channel MOSFET model

PMOS

P-channel MOSFET model

NMF

N-channel MESFET model

PMF

P-channel MESFET model

|**Code**        |**Model Type**        |

| --- | --- |

| R | Semiconductor resistor model |

| C | Semiconductor capacitor model |

| L | Inductor model |

| SW | Voltage controlled switch |

| CSW | Current controlled switch |

| URC | Uniform distributed RC model |

| LTRA | Lossy transmission line model |

| D | Diode model |

| NPN | NPN BJT model |

| PNP | PNP BJT model |

| NJF | N-channel JFET model |

| PJF | P-channel JFET model |

| NMOS | N-channel MOSFET model |

| PMOS | P-channel MOSFET model |

| NMF | N-channel MESFET model |

| PMF | P-channel MESFET model |

Although it is beyond the scope of this document to go into detail there are some other points about models that are worth mentioning.

* Models for the basic resistors, capacitors and inductors used in a schematic are usually not shown in the netlist;

* Some device models have a full list of parameters, some may only have a partially completed list. Missing parameters in models are simply replaced by default values.

* Different simulators support different sets of models so in some cases the simulator may warn the user that some parameters are unrecognised and so are ignored. This often has little effect on the simulation results but if the user is particularly concerned about their effects then the only options are to find a model which only uses parameters recognised by ngspice or change to using a simulator (such as LTspice) that supports all the relevant parameters.

## .subckt definitions

Not all devices are described by .model statements.

Models of more complex devices such as Thyristors (SCRs, Triacs and also Diacs), Insulated Gate Bipolar Transistors (IGBTs), operational amplifiers (opamps) and even many MOSFETs are often made up by connecting lower level devices to make a circuit that behaves like the desired device. This is called a **subcircuit**. The spice netlist of this subcircuit is then used to create a type of device model defined by what is called a **.subckt**. The low level components in subcircuits are described by the same sort of models (those lists of parameters or coefficients) as for the basic diodes etc., already referred to so a .subckt will often contain a list of .model statements describing the devices that are used to build the .subckt itself. Complex .subckts may even call other .subckts.

## Behavioural models

Using Behavioural Voltage and Current Sources and expressions it is possible to create what are called **behavioural models** of components. These are models that behave like a device but which have little or none of the actual underlying realistic circuit defined and are mostly - or perhaps completely - described by explicitly defined expressions (equations). The models for most devices internally comprising more than one active component, i.e. ICs, are largely behavioural. This is a way of hiding the detailed information about the manufacturer's process technology that low level spice modelling reveals.

The use of expressions and behavioural sources in EasyEDA is explained later in the book.

## What if there is no model available for a device?

Not all devices have spice models that can be run in ngspice. There are a number of possible reasons for this.

1) Some models are encrypted and can only be run in certain proprietary simulation tools;

2) Some proprietary simulators support models that are not available in ngspice;

3) Some devices have models that only run in specific non-spice based simulation tools and which, for whatever reason, cannot be translated into spice models;

4) Some devices do not have publically available models;

5) Many devices predating the creation of the original spice program do not have models;

6) Models for some devices simply do not exist because the manufacturers have never created them;

7) Some models may be unavailable in EasyEDA because they are restricted by copyright or end user licenses so they can only be run in certain proprietary simulation tools or cannot be shared publicly.

In cases (1) to (3), there is no way they can be run in ngspice. They must be run in the simulation tools for which they were written.

In cases (4) to (7), it is sometimes possible to find an equivalent, alternative or similar device for which a spice model is available. The user must exercise caution and use their judgement in deciding if such an approach offers satisfactory simulation results.

It must be noted that spice was not originally written with support for thermionic devices (valves or tubes) so models for such devices exist only in .subckt form. They are usually created by enthusiasts rather than manufacturers and so they (a) can be hard to find and (b) should be used with caution. EasyEDA does have a library of valve models gathered from sources that we believe have written reasonably accurate models.

Note that models obtained from manufacturers are often subject to copyright restrictions. Please respect any copyright notices contained either in end user license agreements that may have to be accepted prior to the granting of access to a downloadable copy of a model or in the models themselves.

Similarly, models contained in the libraries of commercial simulation tools are subject to copyright restrictions.

It is often possible to find device models offered in forums, discussion groups and various online collections of models. Again, the user must exercise caution and use their judgement in deciding if such models really are suitable. Often it is not possible to establish where they originate from so their validity is very hard to verify. It is also possible that such models have been copied in breach of the originators’ copyright.

## The relationship between spice models and device datasheets

Although some of the device models in EasyEDA have been specially written so that the user can easily tailor them to simulate a range of devices by editing parameters that can be found directly in - or inferred from - device datasheets (see: About the relationship between spice models and real world behaviour below), most of them are off-the-shelf models from the device manufacturers.

It is important to understand that, for many of these off-the-shelf models, the underlying equations and therefore the .model parameters and .subckt definitions bear little relationship to the sort of information that is given in typical component datasheets. Therefore it is usually not possible to take a device datasheet and simply write down a device models from the information given in it.

Whilst it is possible to extract spice parameters for a variety of devices from device datasheets and from actual device measurements, it is beyond the scope of this document to describe how this can be done.

More information about what the model parameters mean in diodes, bipolar transistors and MOSFETs, is available from:

http://www3.imperial.ac.uk/pls/portallive/docs/1/56133736.PDF

with individual slide sets:

http://www3.imperial.ac.uk/pls/portallive/docs/1/7292571.PDF

http://www3.imperial.ac.uk/pls/portallive/docs/1/7292572.PDF

http://www3.imperial.ac.uk/pls/portallive/docs/1/7292573.PDF

For more detailed information about bjt's in particular, this book:

>[Modelling the Bipolar Transistor by Ian Getreu](http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=01480193)

is available from:

http://www.lulu.com/spotlight/iangetreu

And:

http://www.amazon.com/Modeling-Bipolar-Transistor-Ian-Getreu/dp/B000EYPQLU

Another excellent (and free) book about transistor modelling, is available by going to:

http://www.aeng.com/spice_modeling.htm

and registering to get a copy of:

>[Definitive Handbook of Transistor Modeling](http://www.aeng.com/pdf/RGVmaW5pdGl2ZSBIYW5kYm9vayBvZiBUcmFuc2lzdG9yIE1vZGVsaW5n.pdf)

More information about ngpsice is available from here:

http://ngspice.sourceforge.net/presentation.html

More information about Larry Nagel and SPICE is available from here:

http://www.omega-enterprises.net/The%20Origins%20of%20SPICE.html

Larry’s PhD dissertation Dissertation:

Laurence W. Nagel., “SPICE2: A Computer Program to Simulate Semiconductor Circuits,”

Memorandum No. ERL-M520, University of California, Berkeley, May 1975.

http://www.eecs.berkeley.edu/Pubs/TechRpts/1975/ERL-520.pdf

is actually very readable and instructive.

For more information about electronic circuit simulation and spice in particular, see:

http://en.wikipedia.org/wiki/Electronic_circuit_simulation  

And:

http://en.wikipedia.org/wiki/SPICE

## The relationship between spice models and real world behaviour

Not all spice models are created equal.

Here are just some of the things to be aware of.

Models of the same device from different manufacturers may offer differing degrees of accuracy. Sometimes models are kept simple in the interests of speeding up the simulations at the expense of accuracy. Sometimes they are complex because accuracy is considered to be more important than simulation speed. Models may contain some text at the beginnings of them to describe some of their limitations or their special features. It is often useful to read this information as it can help improve the convergence of simulations using them.

Not all diode models simulate reverse breakdown voltage.

Zener diode models can be of varying accuracy and are best put into test jigs to run a curve trace on them to compare them with the datasheet. Zener diodes are sometimes used as white noise sources. Zener models do not accurately generate the levels and spectrum of noise seen in real devices.

None of the bjt models simulate the reverse bias base-emitter breakdown voltage. Very few model collector-emitter or collector-base junction breakdown voltages.

Some models, particularly of high speed and high frequency devices may include package parasitics such as lead inductances and pin capacitances. Such models are almost always .subckt definitions of devices defined by .model statements but which have the parasitics connected to form a subckt. If the high frequency behaviour is not important, simulation speed can be improved by using only the .model statement without the parasitics. This .model can be cut and pasted out of the .subckt definition but often the .model statement will be for a transistor that is defined as a .model in its own right somewhere else on the manufacturer’s site or as an equivalent from another vendor.

Thyristor and Triac models can be of varying accuracy or simulate only a limited selection of all the device parameters.

EasyEDA has an in-house behavioural Thyristor macromodel and a behavioural Triac macromodel.

As far as possible, the EasyEDA in-house Thyristor and Triac models model almost all the datasheet parameters of the target device with the exception of di/dt behaviour with inductive loads. These devices can be tailored to model almost any device simply using the values taken from the datasheet for the target device.

Metal Oxide Varistors (MOVs) are a nightmare to model and are best avoided! Even the commercially available models sometimes do not run reliably in all conditions.

Some opamp models are highly detailed and can be very accurate but care must be taken to check that they are written using a syntax that is compatible with ngspice. Devices tailored for some of the commercial simulators will not run in ngspice without some syntax changes. Some may require special **.options** to be invoked for the simulator.

Beware that even some quite complex opamp models do not simulate supply current drains even as simple DC quiescent currents let alone the dynamic behaviour with load currents added in. This can be an advantage since it reduces the signal currents that have to be simulated. It also means that there is absolutely no point in including any supply rail decoupling for those device that are known to not model supply current drains since they do not draw any current: they only use the supply voltage to define things like common mode range or output swing.

Here is an example of a third party opamp model that does not model supply or output currents:

>[LM108 test jig](https://easyeda.com/editor#id=0072ad0fd0ef4bca8e14ce8a378449fc)

Some opamp models may make no attempt to accurately simulate the output stage behaviour versus load current. Similarly, many device models do not simulate the behaviour of inputs and outputs when they are taken above or below the supply rails.

Few device models simulate the excessive supply current drain of a supply reversed misconnection or a correctly connected device that is subject to a supply voltage above the stated absolute maximum supply differential.

There are a several device models in EasyEDA that have been specially written to reproduce the real world behaviours - such as described above - of the devices that they model.

For example, the EasyEDA in-house opamp behavioural macromodel can be set up to give an output voltage swing anywhere from a rail-to-rail to the more restricted swings of non-rail-to-rail output opamps. The output swing can be asymmetric.

Input resistance, bias and offset current and input offset voltage are modelled.

The input differential and common mode voltage ranges are modelled.

The current drain behaviour of the device if input or output pins are taken above or below the supply rails or if the supply polarities are reversed are modelled. Output polarity reversal due to inputs exceeding the common mode range is modelled for devices that exhibit such behaviour.

Frequency dependent common mode and power supply rejection are modelled.

Noise and temperature dependent effects are not modelled at present.

EasyEDA has an in-house behavioural macromodel which can be tailored to model a wide range of 3 terminal fixed and adjustable positive and negative linear voltage regulators which feature similar real-world behaviour to the opamp models.

For all of the in-house EasyEDA models, more information about them can be found in the .subckt definition itself simply by viewing the spice netlist of any saved circuit they have been put into.

## How to change the model attached to a symbol

**Please note that before attempting to edit device models, it is essential that the user is familiar with and understands the relationship between spice pin names and numbering, described in the section on `Schematic symbols: prefixes and pin numbers`.**

**To find device simulation models available in EasyEDA, see:**

https://easyeda.com/forum/topic/How_to_find_simulatable_parts_and_run_a_simulation_in_EasyEDA-1YgasK2kC

Right now there are a couple of ways to change the model for a device.

1) Place a device from the EasyEDA Libs and then edit the device model name either in place in the schematic or in the right hand properties panel.


>
For instance, when an NPN bjt is placed in a schematic, it comes in with a default name of editing the model name of 2DC2412R. This name pulls the associated default 2DC2412R model into the spice netlist. Editing the device name from 2DC2412R to 2N2222 will pull the 2N2222 model from EasyEDA's spice model library into the netlist.
The problem here is that until a model search function is up and running this approach is obviously too hit and miss for an arbitrary choice because there is no way to see which models are available to choose from.

2) The second option is a bit more fiddly but it allows almost any unencrypted device model to be run in a simulation. The process is similar for both .model and .subckt defined models.

### For .MODEL defined models

1) Find a spice .model for your target device;

2) Copy and paste it into a text placeholder (the T hotkey) in your schematic (but please respect the EULA and copyright of commercial files);

3) In the right hand properties panel, change the text type from comment to spice;


**
Properties > Text type > spice**

4) Place a symbol for the device from the EasyEDA Libs palette onto the schematic;

5) Edit the model name to the exact name of the model in the pasted file.

6) Done!

There's an example of this here:

>[Playing with model parameters](https://easyeda.com/editor#id=8b454f0e409e4ebf8c3f0e96b458d1e0)

This is another example showing using a generic depletion mode MOSFET.

It also shows a way to hack a MOSFET defined by a LEVEL 3 .model statement but which has a problem with some of the parameters not being recognised as being part of the model by ngspice, so that it can still be used directly with the MOSFET symbol.

In this example the L and W parameters of the original model are recognised as part of the .model statement. Note also that some of the other parameters are also simply not recognised by ngspice.

Here's how:

1) Find a spice .model for your target device;

2) Copy and paste the .model statement into the schematic canvas;

3) Turn it into a spice directive:


        >**
Text Attributes > Text type > spice**

4) Place an N channel depletion mode MOSFET symbol onto the schematic;

5) Edit the 'model' attribute for M1 to include the unrecognised or modified L and W parameters so they look like this:

>**IXTT20N50D L=2E-6 W=5.5**


>This can be done either in place or via:


>**
Part Attributes > Model > IXTT20N50D L=2E-6 W=5.5**

Note that adding an asterisk at the start of the two lines in the .model statement that define the L and W (and any other unrecognised parameters as deemed necessary) parameters will comment them out. This stops these parameters being reported as model issues in the simulation report but it is not required to do so.

This process is illustrated in the following example:

>[N channel depletion mode MOSFET using a .model statement](https://easyeda.com/editor#id=07a2743a497647419fc68f253e84c295)

### For .SUBCKT defined models

The process described above works fine for simple .model defined models but for .subckt defined models it is a little more complicated because you need to tell EasyEDA that the model is a .subckt and not a simple .model.

Even some humble diode models are in fact .subckt defined to include things like package parasitics. For example, compare the 1N4148 and the 1N4148W-V models in the netlist.

There are three stages in attaching a .subckt to a symbol that already has a spice prefix of 'X' and so is expecting to call a .subckt statement.

* Place the .subckt text into the schematic and activate it;

* Place the symbol in the schematic;

* Change the name of the symbol to exactly the same as the name of the .subckt;

The detailed steps to associate a new .subckt model to the symbol are:

1) Find a spice .SUBCKT for your target device;

2) Copy and paste it into a text box (the T hotkey) in your schematic (but please respect the EULA and copyright of commercial files);

3) In the right hand properties panel, change the text type from comment to spice;

**Text Attributes > Text type > spice**

4) Place a symbol for the device from the EasyEDA Libs palette onto the schematic;

5) Edit the model name to the exact name of the model in the pasted file;

6) Press the 'I' Hotkey or:


Click the 'Edit Symbol...' button in the Properties panel:


**
Part Attributes > Edit Symbol…**

or do:


**
Right-click on the symbol > Edit Symbol**

7) In the 'Modify your symbol information' dialogue box, check that the 'Spice Prefix' is 'X';

8) Check that the NUMBER of pins in 'Edit Pin Map information' is exactly the same as in the .SUBCKT pasted into the schematic: if it is not then the wrong symbol has been placed for the chosen .SUBCKT (or vice versa) so a different symbol (or .SUBCKT) must be chosen.

Note that 'number of pins' here means how many pins, not the pin numbers or names used to describe the nets they connect to in the .subckt netlist;

9) Check that the ORDER of the pins in 'Edit Pin Map information' is exactly the same as in the .SUBCKT pasted into the schematic. This can be very confusing because the pin NAMES may be different between the symbol and the .SUBCKT so it is first necessary to reconcile the two sets of names before attempting to confirm their order.

10) Click OK in the 'Modify your symbol information' dialogue box;

11) Done!

This process is illustrated in the following example:


>[
Attaching a .subckt to a symbol 01](https://easyeda.com/editor#id=38bb9615b9ae4194825f924025d312ca)

Some of the EasyEDA symbols such as bjts and all the MOSFETs have a Spice Prefix of 'M' and so are expecting to call a .model statement. To associate a .subckt to a symbol with a Spice Prefix of 'M' there are four stages.

So, in the following example, the NMOS_E symbol placed into the schematic from the EasyEDA Libs palette must be edited to change the 'Spice Prefix' of the symbol from 'M' (for a .model defined part) to 'X' (for a .subckt defined part).

* Place the .subckt text into the schematic and activate it;

* Place the symbol in the schematic;

* Change the name of the symbol to exactly the same as the name of the .subckt;

* Change the 'Spice Prefix' of the symbol from 'M' (for a .model defined part) to 'X' (for a .subckt defined part).

The detailed steps to associate a new model to a symbol and to tell EasyEDA that a device model is a .subckt and not a simple .model are:

1) Find a spice .SUBCKT for your target device;

2) Copy and paste it into a text box (the T hotkey) in your schematic (but please respect the EULA and copyright of commercial files);

3) In the right hand properties panel, change the text type from comment to spice;


**
Text Attributes > Text type > spice**

4) Place a symbol for the device from the EasyEDA Libs palette onto the schematic;

5) Edit the model name to the exact name of the model in the pasted file;

6) Press the 'I' Hotkey or:


Click the 'Edit Symbol...' button in the Properties panel:


**
Part Attributes > Edit Symbol…**

or do:


**
Right-click on the symbol > Edit Symbol**

7) In the 'Modify your symbol information' dialogue box, change the 'Spice Prefix' from 'M' (for a .model defined part) to 'X' (for a .subckt defined part);

8) Check that the NUMBER of pins in 'Edit Pin Map information' is exactly the same as in the .SUBCKT pasted into the schematic: if it is not then the wrong symbol has been placed for the chosen .SUBCKT (or vice versa) so a different symbol (or .SUBCKT) must be chosen.


Note that 'number of pins' here means how many pins, not the pin numbers or names used to describe the nets they connect to in the .subckt netlist;

9) Check that the ORDER of the pins in 'Edit Pin Map information' is exactly the same as in the .SUBCKT pasted into the schematic. This can be very confusing because the pin NAMES may be different between the symbol and the .SUBCKT so it is first necessary to reconcile the two sets of names before attempting to confirm their order.

10) Click OK in the 'Modify your symbol information' dialogue box;

11) Done!

This process is illustrated in the following example:

>[Attaching a .subckt to a symbol 02](https://easyeda.com/editor#id=38bb9615b9ae4194825f924025d312ca)

Another example of the process described above to change the Spice Prefix of a symbol is illustrated with the same EasyEDA N channel depletion mode MOSFET symbol from the EasyEDA Libs that was used earlier with the IXTT20N50D .model statement. In this example the MOSFET symbol is attached to a .subckt that has been created from the orignal IXTT20N50D .model statement in order to wrap up the L=2E-6 W=5.5 parameters and so make using the original model easier.

>[An N-channel depletion mode MOSFET using an EasyEDA .subckt](https://easyeda.com/editor#id=97747a105ae44816b7a29e73bebc29da)

### Attaching models to custom symbols

This is basically the same as attaching a model to any of the predefined symbols from the EasyEDA Libs except that the symbol is one that has been created from scratch or by editing an existing symbol. The rules for assigning and checking that the spice prefix matches the type of model to be attached ('M' for .model or 'X' for .subckt) and checking that the spice pin numbering matches that of the type of device defined by the .model statement or by the pin sequence of a .subckt defined model.

# Schematic symbols: prefixes and pin numbers

**Please note that before attempting to edit device models, it is *essential* that the user is familiar with and understands the relationship between spice pin names and numbering, described in this section.**

Device and subcircuit symbols created for use in schematics that are intended to be run as spice simulations, in addition to having a PCB Prefix that is used for the reference designator in the schematic, also have a Spice Prefix. They also have two sets of pin numbers: PCB pins and Spice pins.

## PCB and Spice Prefix

The rules on the assignment of the PCB Prefix or reference designator of a schematic symbol are somewhat dependent on the EDA tool and on the user's preferences. Depending on how a device is graphically represented by it's schematic symbol it may have a different PCB Prefix or reference designator. For example, a single discrete MOSFET device may have a PCB Prefix of Q, M or perhaps TR, whereas if it is part of a monolithic multiple transistor array it may have a PCB Prefix of U or IC.

The rules on the assignment of the Spice Prefix of a schematic symbol are strict. This is because the Spice Prefix is used to tell the simulator which circuit element the symbol represents and therefore which simulation model it is to use.

Simulation models for most of the spice circuit elements are in the form of a single-line **.model** statement however some of them may be in the form of a multi-line **.subckt** subcircuit definition.

For example, some MOSFETs may be described by a .model statement in which case their Spice Prefix is M but many MOSFETs are described by a .subckt and so their Spice Prefix is X.

Therefore, irrespective of the PCB Prefix chosen for a schematic symbol, the Spice Prefix for a schematic symbol representing a given circuit element must match the type of model required to simulate that instance of that circuit element in your schematic.

For example, if there are two different n-channel MOSFETs in a schematic;

Q1, a BSS123 which is modelled by a .model statement:

~~~

*BSS123

*SRC=BSS123 ;DI_BSS123 ;MOSFETs N; Enh ;100V 0.170A 1.00ohms

*Diodes Inc. MOSFET

.MODEL DI_BSS123 NMOS( LEVEL=1 VTO=1.00 KP=6.37m GAMMA=1.24

+ PHI=.75 LAMBDA=625u RD=0.140 RS=0.140

+ IS=85.0f PB=0.800 MJ=0.460 CBD=19.8p

+ CBS=23.7p CGSO=36.0n CGDO=30.0n CGBO=124n

* -- Assumes default L=100U W=100U --

~~~

and Q2, a BSS127S which is modelled by a .subckt:

~~~

* BSS127S

*---------- BSS127S Spice Model ----------

.SUBCKT BSS127S 10 20 30

* TERMINALS: D G S

M1 1 2 3 3 NMOS L = 1E-006 W = 1E-006

RD 10 1 84.22

RS 30 3 0.001

RG 20 2 29

CGS 2 3 1.958E-011

EGD 12 0 2 1 1

VFB 14 0 0

FFB 2 1 VFB 1

CGD 13 14 2E-011

R1 13 0 1

 D1 12 13 DLIM

DDG 15 14 DCGD

R2 12 15 1

D2 15 0 DLIM

DSD 3 10 DSUB

.MODEL NMOS NMOS LEVEL = 3 VMAX = 8E+005 ETA = 1E-012 VTO = 3.419

+ TOX = 6E-008 NSUB = 1E+016 KP = 0.127 U0 = 400 KAPPA = 1.044E-015

.MODEL DCGD D CJO = 1.135E-011 VJ = 0.9232 M = 0.9816

.MODEL DSUB D IS = 2.294E-010 N = 1.601 RS = 0.1079 BV = 65

+ CJO = 1.956E-011 VJ = 1.514 M = 0.8171

.MODEL DLIM D IS = 0.0001

.ENDS

*Diodes BSS127S Spice Model v1.0 Last Revised 2012/6/6

~~~

then even though both have the same PCB Prefix of Q: Q1 must have a Spice Prefix of M and Q2 must have a Spice Prefix of X.

A list of Spice Prefixes and their associated circuit elements is given in the table below.

**Element description**

**Spice Prefix**

**Spice pin order**

**Comment**

A

XSPICE code model

Depends on model

analogue, digital, mixed signal

B

Behavioural (arbitrary) source

Source+, Source-,

Control+,

Control-

C

Capacitor

Fixed by model but has no polarity

D

Diode

A K

E

Voltage-controlled voltage source (VCVS)

Source+, Source-,

Control+,

Control-

linear, non-linear

F

Current-controlled current source (CCCS)

Source+, Source-,

Vsrcname

linear

Vsrcname is for a voltage source external to the switch.

G

Voltage-controlled current source (VCCS)

Source+, Source-,

Control+,

Control-

linear, non-linear

H

Current-controlled voltage source (CCVS)

Source+, Source-,

Vsrcname

linear

Vsrcname is for a voltage source external to the switch.

I

Current source

Source+, Source-

J

Junction field effect transistor (JFET)

D G S

K

Coupled (Mutual) Inductors

Fixed but must respect winding phases

L

Inductor

Fixed by model but has no polarity

M

Metal oxide field effect transistor (MOSFET)

D G S

N

Numerical device for GSS

O

Lossy transmission line

Fixed by model

P

Coupled multiconductor line (CPL)

Fixed by model

Q

Bipolar junction transistor (BJT)

C B E

R

Resistor

Fixed by model but has no polarity

S

Switch (voltage-controlled)

Switch+, Switch-,

Control+,

Control-

T

Lossless transmission line

Fixed by model

U

Uniformly distributed RC line

Fixed by model

V

Voltage source

Source+, Source-

W

Switch (current-controlled)

Switch+, Switch-,

Vsrcname

Vsrcname is for a voltage source external to the switch.

X

Subcircuit

Depends on subckt

Y

Single lossy transmission line (TXL)

Fixed by model

Z

Metal semiconductor field effect transistor (MESFET)

D G S

| **Element description** | **Spice Prefix** | **Spice pin orde** | **Comment** |

| --- | --- | --- | --- |

| A | XSPICE code model | Depends on model | analogue, digital, mixed signal |

| B | Behavioural (arbitrary) source | Source+, Source-,<br>Control+,<br>Control- |  |

| C | Capacitor | Fixed by model but has no polarity |  |

| D | Diode | A K |  |

| E | Voltage-controlled voltage source (VCVS) | Source+, Source-,<br>Control+,<br>Control- | linear, non-linear |

| F | Current-controlled current source (CCCS) | Source+, Source-,<br>Vsrcname | linear<br><br>Vsrcname is for a voltage source external to the switch. |

| G | Voltage-controlled current source (VCCS) | Source+, Source-,<br>Control+,<br>Control- | linear, non-linear |

| H | Current-controlled voltage source (CCVS) | Source+, Source-,<br>Vsrcname | linear<br><br>Vsrcname is for a voltage source external to the switch. |

| I | Current source | Source+, Source- |  |

| J | Junction field effect transistor (JFET) | D G S |  |

| K | Coupled (Mutual) Inductors | Fixed but must respect winding phases |  |

| L | Inductor | Fixed by model but has no polarity |  |

| M | Metal oxide field effect transistor (MOSFET) | D G S |  |

| N | Numerical device for GSS |  |  |

| O | Lossy transmission line | Fixed by model |  |

| P | Coupled multiconductor line (CPL) | Fixed by model |  |

| Q | Bipolar junction transistor (BJT) | C B E |  |

| R | Resistor | Fixed by model but has no polarity |  |

| S | Switch (voltage-controlled) | Switch+, Switch-,<br>Control+,<br>Control- |  |

| T | Lossless transmission line | Fixed by model |  |

| U | Uniformly distributed RC line | Fixed by model |  |

| V | Voltage source | Source+, Source- |  |

| W | Switch (current-controlled) | Switch+, Switch-,<br>Vsrcname | Vsrcname is for a voltage source external to the switch. |

| X | Subcircuit | Depends on subckt |  |

| Y | Single lossy transmission line (TXL) | Fixed by model |  |

| Z | Metal semiconductor field effect transistor (MESFET) | D G S |  |

For more information on circuit elements in Ngspice, please refer to:

http://ngspice.sourceforge.net/docs/ngspice-manual.pdf#subsection.2.1.2

## PCB and Spice pin numbers

The two sets of pin numbers are:

**PCB pin number**: these are the numbers for the real, physical device pins in its package. They are required so that the pins of a device symbol in a schematic can be mapped onto the physical pins of a PCB footprint. In other words, so that the connections shown in the schematic, end up connected properly by copper on the PCB.

**Spice pin number** or pin order: these are the numbers that map the pins on the symbol to their respective functions in the spice model or subcircuit.

* The spice pin ordering of .model defined models is fixed as shown in the table above.

* The spice pin ordering of .subckt defined models is determined by the .subckt line in the subcircuit.

Actually the spice pin ordering has a slightly deeper meaning.

Spice has no concept of component symbols: they are a construct of the schematic editor.

When a spice netlist is generated, the symbol in the schematic editor is either - in the case of model defined devices such as resistors, capacitors, inductors, diodes, transistors and sources - mapped directly to the relevant models (defined by the device prefix such as R, C, L, D, Q and so on), or in the case of a subcircuit, converted into a subcircuit call statement.

The spice pin ordering for the majority of built-in models such as resistors, capacitors, inductors, diodes, transistors and sources are defined and generally taken care of by the schematic editor, more care has to be taken with the spice pin ordering of subcircuits.

This can be illustrated by a simple opamp with 5 pins: inverting and non-inverting inputs; output and positive and negative supply pins but the principle applies to all spice subcircuits.

The subcircuit call for this opamp might look like this in the spice netlist:

>**X1 input feedback vpos vneg output opamp_ANF01**

Where:

>**X1** is the name of the subcircuit in the top level (i.e. the calling) circuit;

>**input feedback vpos vneg output** are the netnames in the circuit calling (i.e. containing) the subcircuit and:

>**opamp_ANF01** is the name of the subcircuit being called.

* Pay special attention to the order of the netnames in the subcircuit call.

The spice pin ordering for the majority of opamp subcircuits is like that shown in the example below:

~~~

*------------------------------------------------------------------- *

* opamp_ANF01 * * Simplified behavioural opamp *

* Node assignments

*                    noninverting input

*                    |   inverting input

*                    |   |   positive supply

*                    |   |   |   negative supply

*                    |   |   |   |   output

*                    |   |   |   |   |

* spice pin order:   1   2   3   4   5

*                    |   |   |   |   |

.subckt opamp_ANF01 inp inn vcc vee out ; these are the netnames

* used internally to the

* subcircuit.

B1 out 0 + V=(TANH((V(inp)-V(inn))*{Avol}*2/(V(vcc)-V(vee)))*(V(vcc)-V(vee)) + +(V(vcc)+V(vee)))/2

* .ends opamp_ANF01

*

*-------------------------------------------------------------------

~~~

Note that the spice pin order of the subcircuit call is in exactly the same order as that of the pins in the .subckt line of the subcircuit.

Although the physical pin numbering of any device is critical for successfully mapping the pins on a schematic symbol onto a physical package footprint when laying out the PCB, because spice only knows about single devices and does not care about how they are physically packaged, each instance of any device in a spice schematic has to be mapped onto its own copy of the spice model or subcircuit, irrespective of where it is in any physical package.

Therefore, for the physical, package pin numbering of the four opamps in a quad opamp in say, a SOIC14 or a DIP14 package, as shown below, to work with the example subcircuit above, the spice pin ordering would be:

**Opamp A**

**Pin Number**

**Spice Pin Order**

OUT

1

5

IN-

2

2

IN+

3

1

V+

4

3

V-

11

4

**Opamp B**

**Pin Number**

**Spice Pin Order**

OUT

7

5

IN-

6

2

IN+

5

1

V+

4

3

V-

11

4

**Opamp C**

**Pin Number**

**Spice Pin Order**

OUT

8

5

IN-

9

2

IN+

10

1

V+

4

3

V-

11

4

**Opamp D**

**Pin Number**

**Spice Pin Order**

OUT

14

5

IN-

13

2

IN+

12

1

V+

4

3

V-

11

4

| **Opamp A** | **Pin Number** | **Spice Pin Order** |

| --- | --- | --- |

| OUT | 1 | 5 |

| IN- | 2 | 2 |

| IN+ | 3 | 1 |

| V+ | 4 | 3 |

| V- | 11 | 4 |

|  |  |  |

| **Opamp B** | **Pin Number** | **Spice Pin Order** |

| OUT | 7 | 5 |

| IN- | 6 | 2 |

| IN+ | 5 | 1 |

| V+ | 4 | 3 |

| V- | 11 | 4 |

|  |  |  |

| **Opamp C** | **Pin Number** | **Spice Pin Order** |

| OUT | 8 | 5 |

| IN- | 9 | 2 |

| IN+ | 10 | 1 |

| V+ | 4 | 3 |

| V- | 11 | 4 |

|  |  |  |

| **Opamp D** | **Pin Number** | **Spice Pin Order** |

| OUT | 14 | 5 |

| IN- | 13 | 2 |

| IN+ | 12 | 1 |

| V+ | 4 | 3 |

| V- | 11 | 4 |

|  |  |  |

The physical package pin numbering reflects that of each opamp in the package.

The spice pin ordering is the same for each instance of the individual opamps.

Of course there is only one physical instance of each supply pin on the schematic symbol for the quad opamp in this example but each spice subcircuit must have the supply pins explicitly defined.

Exactly how this is handled is at the schematic symbol level depends on how the schematic capture package handles symbols for multiple devices with shared supply pins but the generation of a spice netlist from the schematic will always generate the complete set of pins required in the subcircuit calls.

In cases where the subcircuit is built by the user as opposed to where it is supplied by a vendor for a particular device, exactly the same rules apply except that it is up to the user to specify the subcircuit pin order and to construct the symbol appropriately.

Although as described earlier, built-in spice models usually have defined spice pin orders, not all subcircuits have the same spice pin numbering. Therefore if your spice circuit throws errors - especially if there are warnings about pin numbers or pin names - it is worth remembering to check that the pin order of the symbol that is netlisted to form the calling statement matches that of the subcircuit that is being called!

# Custom modelling

This is an advanced topic and this section will be filled out when time permits.

However, browsing through some of the EasyEDA in-house models can be informative because, although they do not come with a 'How it works' written into them, there is some documentation in their .subckt definitions that may give some insights into the wild and wonderful world of custom modelling.

Some examples to look through the netlists of are:

>[LDR test](https://easyeda.com/editor#id=a21460865ebc4ffd8434d10946c48ec9)

>[Electret microphone model](https://easyeda.com/editor#id=b4a2a22f33324ed2afe4dcd012a0f564)

>[Electret microphone model .subckt](https://easyeda.com/editor#id=46a20a0af877436fa0d4e8ff293cd5b1)

>[Electret microphone model test jig](https://easyeda.com/editor#id=302cb429fc5b4d2f946eaf59b9f72266)

>[LM56EE demo jig](https://easyeda.com/editor#id=41c37ad8190340babd5b36978dfadb2a)

>[How to include a 5 Pin Comparator in a schematic](https://easyeda.com/editor#id=26936cd661744564accff2961cb28c17)

and this project:

>[Easy logic device simulation in V2.3.x onwards](https://easyeda.com/example/Easy_logic_device_simulation_in_V2_3_x_onwards-RaKIG2oJ5)

# Making measurements of simulation results

In the same way that digital storage oscilloscopes (DSO) allow measurements to be made of signals displayed on the screen using cursors and directly reading values from their positions and from mathematical analysis of the waveform data stored in the DSO memory, EasyEDA allows measurements to be made of simulation results directly using cursors and by analysis of the data used to create the WaveForm trace display using the `meas` command.

## Using the WaveForm display cursors

The WaveForm X and Y cursor functions are a simple and quick way to make measurements of points in waveforms and to make measurements of differences between points.

WaveForm allows the display of traces in any selection of up to three vertically stacked plot panes. The Y axes automatically scale to fit the units and the range of the traces being displayed. Traces can be hidden but at least one trace must be visible. X and Y trace data can be seen on-screen just by moving the mouse cursor around the plot area of a pane with the readout adapting to the Y axes in each pane.

Delta X and delta Y trace data can be seen on-screen using a Left-Click and Drag select box, with the readout adapting to the Y axes in each pane. Returning the cursor to within a small radius of the starting point of the select box - without releasing the Left-Click - returns the readout to X and Y trace data.

The cursor placement and results produced are volatile, meaning that they cannot be copied and pasted. They are not saved as part of a saved WaveForm file. However, using a screenshot utility, it is possible to save an image of the WaveForm display showing the cursor positions and their associated readout.

Note that the screenshot utility must have a user definable time delay to allow cursor placement to be carried out between initiating the screenshot and the screenshot actually being taken.

For more information on displaying simulation results in Waveform, please refer to the section on **WaveForm** in the [the EasyEDA Tutorial](https://easyeda.com/Doc/Tutorial/spiceSimulation.htm#WaveForm).

## Using the meas command

The meas command is used to analyse the output data of a dc, ac, tran or fft (or spec) simulation. The command is executed immediately after the simulation has finished.

## The meaning of terms in MEAS commands

The meas type **{DC|AC|TRAN|SP}** depends on the data which are to be evaluated, either originating from a DC, AC analysis, TRANsient or SPectrum analysis (using the fft (or spec) analysis) simulation.

**result** will be a vector containing the result of the measurement.

**trig_variable, targ_variable**, and **out_variable** are vectors stemming from the simulation, e.g. a voltage vector v(out).

**VAL=val** expects a real number val. val may also be a real parameter or an expression enclosed by “ or {} that expands to a real number.

**TD=td** and **AT=time** expect a time value if the meas type is **tran**. For **ac** and **sp**, **AT** will be a frequency value and **TD** is ignored.

For **dc** analysis **AT** is a voltage (or current), and **TD** is ignored.

**CROSS=#** requires an integer number #. **CROSS=LAST** is possible as well. The same is expected by **RISE** and **FALL**.

Frequency and time values may start at 0 and extend to positive real numbers. Voltage (or current) inputs for the independent (scale) axis in a dc analysis may start or end at arbitrary real valued numbers.

## Examples of the forms and syntaxes of MEAS commands

### Trig Targ

A meas command using the Trig Targ syntax of **General Form 1** measures the difference in dc voltage, frequency or time between two points selected from one or two output vectors. The following examples all are using transient simulation. Measurements for tran analysis start after a delay time td. If other examples are run with ac simulation or spectrum analysis, time may be replaced by frequency whilst after a dc simulation, the independent variable may become a voltage or current.

**General Form 1: **

~~~

MEAS {DC | AC | TRAN | SP} result TRIG trig_variable VAL=val

<TD=td> <CROSS=# | cross="LAST">

<RISE=# | rise="LAST"> <FALL=# | fall="LAST">

<TRIG at="time"> TARG targ_variable VAL=val <TD=td>

<CROSS=# | cross="LAST">

<RISE=# | rise="LAST"> <FALL=# | fall="LAST">

<TARG at="time">

~~~

Measure statement example:

`meas tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 RISE=2`

measures the time difference between v(1) reaching 0.5 V for the first time on its first rising slope (TRIG) versus reaching 0.5 V again on its second rising slope (TARG); i.e. it measures the signal period.

Output:

`tdiff = 1.000000e-003 targ= 1.083343e-003 trig= 8.334295e-005` 

Measure statement example:

`meas tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 RISE=3` 

measures the time difference between v(1) reaching 0.5 V for the first time on its rising slope versus reaching 0.5 V on its rising slope for the third time (i.e. two periods).

Measure statement example:

`meas tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 FALL=1`

measures the time difference between v(1) reaching 0.5V for the first time on its rising slope versus reaching 0.5 V on its first falling slope.

Measure statement example:

`meas tran tdiff TRIG v(1) VAL=0 FALL=3 TARG v(2) VAL=0 FALL=3`

measures the time difference between v(1) reaching 0V its third falling slope versus v(2) reaching 0 V on its third falling slope.

Measure statement example:

`meas tran tdiff TRIG v(1) VAL=-0.6 CROSS=1 TARG v(2) VAL=-0.8 CROSS=1`

measures the time difference between v(1) crossing -0.6 V for the first time (any slope) versus v(2) crossing -0.8 V for the first time (any slope).

Measure statement example:

`meas tran tdiff TRIG AT=1m TARG v(2) VAL=-0.8 CROSS=3`

measures the time difference between the time point 1ms versus the time when v(2) crosses -0.8 V for the third time (any slope).

### Find ... When

The FIND and WHEN functions allow to measure any dependent or independent time, frequency, or dc parameter, when two signals cross each other or a signal crosses a given value.

Measurements start after a delay TD and may be restricted to a range between FROM and TO.

**General Form 2:**

~~~

MEAS {DC | AC | TRAN | SP } result WHEN out_variable=val

<TD= td> <FROM=val> <TO= val>

<CROSS=# | cross="LAST">

<RISE| rise="LAST"> <FALL=# | fall="LAST">

~~~

Measure statement example:

`meas tran teval WHEN v(2)=0.7 CROSS=LAST` 

measures the time point when v(2) crosses 0.7 V for the last time (any slope).

**General Form 3:**

 

~~~

MEAS {DC | AC | TRAN | SP } result WHEN out_variable=out_variable2

<TD= td> <FROM= val> <TO= val>

<CROSS=# cross="LAST">

<RISE | rise="LAST"> <FALL=# | fall="LAST">

~~~

Measure statement example:

`meas tran teval WHEN v(2)=v(1) RISE=LAST`

measures the time point when v(2) and v(1) are equal, v(2) rising for the last time.

**General Form 4:**

~~~

MEAS {DC | AC | TRAN | SP } result FIND out_variable WHEN out_variable2=val

<TD= td> <FROM= val> <TO= val>

<CROSS=# | cross="LAST"> <RISE | rise="LAST">

<FALL=# | fall="LAST">

~~~

Measure statement example:

`meas tran yeval FIND v(2) WHEN v(1)=-0.4 FALL=LAST` 

returns the dependent (y) variable drawn from v(2) at the time point when v(1) equals a value of -0.4, v(1) falling for the last time.

**General Form 5:**

~~~

MEAS {DC | AC | TRAN | SP } result FIND out_variable WHEN out_variable2=val=out_variable3

<TD= td> <CROSS=# | cross="LAST"> <RISE | rise="LAST"> <FALL | fall="LAST">

~~~

Measure statement example:

`meas tran yeval FIND v(2) WHEN v(1)=v(3) FALL=2` 

returns the dependent (y) variable drawn from v(2) at the time point when v(1) crosses v(3), v(1) falling for the second time.

 

**General Form 6:**

`MEAS {DC | AC | TRAN | SP } result FIND out_variable AT=val`

Measure statement example:

`meas tran yeval FIND v(2) AT=2m` 

returns the dependent (y) variable drawn from v(2) at the time point 2 ms (given by AT=time).

### AVG | MIN | MAX | PP | RMS | MIN_AT | MAX_AT

**General Form 7:**

~~~

MEAS {DC | AC | TRAN | SP } result {AVG | MIN |MAX| PP | RMS | MIN_AT | MAX_AT} out_variable

<TD= td> <FROM=val> <TO=val>

~~~

Measure statement example:

`meas tran ymax MAX v(2) from=2m to=3m`

returns the maximum value of v(2) inside the time interval between 2 ms and 3 ms.

Measure statement example:

`meas tran tymax MAX_AT v(2) from=2m to=3m` 

returns the time point of the maximum value of v(2) inside the time interval between 2 ms and 3 ms.

Measure statement example:

`meas tran ypp PP v(1) from=2m to=4m` 

returns the peak to peak value of v(1) inside the time interval between 2 ms and 4 ms.

Measure statement example:

`meas tran yrms RMS v(1) from=2m to=4m` 

returns the root mean square value of v(1) inside the time interval between 2 ms and 4 ms.

Measure statement example:

`meas tran yavg AVG v(1) from=2m to=4m` 

returns the average value of v(1) inside the time interval between 2 ms and 4 ms.

### INTEG

A meas statement with the INTEG form returns the area under out_variable inside the time interval between FROM val and TO val.

 

**General Form 8:**

~~~

MEAS {DC | AC | TRAN | SP} result INTEG<RAL> out_variable

<TD=td> <FROM=val> <TO=val>

~~~

Measure statement example:

`meas tran yint INTEG v(2) from=2m to=3m` 

returns the area under v(2) inside the time interval between 2 ms and 3 ms.

### DERIV

Please note that meas {DC|AC|TRAN|SP} result DERIV<ATIVE> ... is not yet available in ngspice.

### More examples of measure statements

~~~

meas tran inv_delay 2 trig v(in) val='vp/2' td=1n fall=1 targ v(out) val='vp/2' rise=1

meas tran test_data1 trig AT=1n targ v(out) val='vp/2' rise=3

meas tran out_slew trig v(out) val=' 0.2*vp' rise=2 targ v(out) val=' 0.8*vp' rise=2

meas tran skew when v(out)=0.6

meas tran skew2 when v(out)=skew_meas

meas tran skew3 when v(out)=skew_meas fall=2

meas tran skew4 when v(out)=skew_meas fall=LAST

meas tran skew5 FIND v(out) AT=2n

meas tran v0_min min i(v0) from='dfall' to='dfall+period'

meas tran v0_avg avg i(v0) from='dfall' to='dfall+period'

meas tran v0_integ integ i(v0) from='dfall' to='dfall+period'

meas tran v0_rms rms i(v0) from='dfall' to='dfall+period'

meas dc is_at FIND i(vs) AT=1

meas dc is_max max i(vs) from=0 to=3.5

meas dc vds_at when i(vs)=0.01

meas ac vout_at FIND v(out) AT=1MEG

meas ac vout_atd FIND vdb (out) AT=1MEG

meas ac vout_max max v(out) from=1 k to=10MEG

meas ac freq_at when v(out)=0.1

meas ac vout_diff trig v(out) val=01 rise=1 targ v(out) val=01 fall=1

meas ac fixed_diff trig AT=10k targ v(out) val=0.1 rise=1

meas ac vout_avg avg v(out) from=10k to=1MEG

meas ac vout_integ integ v(out) from=20k to=500k

meas ac freq_at2 when v(out)=01 fall=LAST

meas ac vout_rms rms v(out) from=10 to=1G

~~~

The following examples illustrate some of the measurements that can be made this way.

>[Measuring WaveForm parameters 01](https://easyeda.com/editor#id=b91ef5c0dbf04a478f3573227affa625)

>[Measuring WaveForm parameters 02](https://easyeda.com/editor#id=bcd3a7d6b7b9451db9c2cb2c1e3ce2e3)

>[Measuring settling time](https://easyeda.com/editor#id=34e0665e96a1407590d3a5544891a60e)

>[Find gain and bandwidth](https://easyeda.com/editor#id=f7e5299c32794f4482fa41178f2627be)


Notes for manual construction of ToC in Markdown.  Based on:

https://stackoverflow.com/questions/11948245/markdown-to-create-pages-and-table-of-contents

# Table of contents

1. >[Introduction](#introduction)

2. >[Some paragraph](#paragraph1)

    1. >[Sub paragraph](#subparagraph1)

3. >[Another paragraph](#paragraph2)

<a name="introduction"></a>

## This is the introduction

Some introduction text, formatted in heading 2 style

Put the link above the heading text so that the heading is shown as the 1st line of the section

 <a name="paragraph1"></a>

## Some paragraph

The first paragraph text

<a name="subparagraph1"></a>

### Sub paragraph <a name="subparagraph1"></a>

This is a sub paragraph, formatted in heading 3 style

<a name="paragraph2"></a>

## Another paragraph

The second paragraph text