NgSpice a mixed-level/signal circuit simulaton

External libraries (GTK, GSL, SDL, Allegro, OpenGL, etc) questions.
D.J.Peters
Posts: 7099
Joined: May 28, 2005 3:28
Location: Germany

NgSpice a mixed-level/signal circuit simulaton

Postby D.J.Peters » Aug 14, 2016 1:28

With ngspice you can simulate/analyse analog,digital and verilog circuits.

Homepage: http://ngspice.sourceforge.net/

Download: https://sourceforge.net/projects/ngspic ... rework/26/
(be sure you get the doc ngspice-26-manual.pdf also)

ngspice comes with a shared library see also: http://ngspice.sourceforge.net/shared.html

Here are the FreeBASIC include file for libngspice.so and ngspice.dll .

Joshy

file: "ngspice.bi"

Code: Select all

#ifndef __NGSPICE_BI__
#define __NGSPICE_BI__

' header file for shared library ngspice
' Copyright 2013 Holger Vogt
' Modified BSD license

' Interface between a calling program (caller) and ngspice *.dll / *.so

' ngSpice_Init(SendChar*, SendStat*, ControlledExit*, SendData*, SendInitData*, BGThreadRunning*, void*)
' After caller has loaded ngspice.dll, the simulator has to be initialized
 'by calling ngSpice_Init(). Address pointers of several callback functions defined in the caller are sent to ngspice.dll.

' Callback funtion typedefs
' SendChar       typedef of callback function for reading printf, fprintf, fputs
' SendStat       typedef of callback function for reading status string and precent value
' ControlledExit typedef of callback function for tranferring a signal upon
'                ngspice controlled_exit to caller. May be used by caller to detach ngspice.dll.
' SendData       typedef of callback function for sending an array of structs containing
'                data values of all vectors in the current plot (simulation output)
' SendInitData   typedef of callback function for sending an array of structs containing info on
'                all vectors in the current plot (immediately before simulation starts)
' BGThreadRunning typedef of callback function for sending a boolean signal (true if thread is running)

' The void pointer may contain the object address of the calling
' function ('self' or 'this' pointer), so that the answer may be directed
' to a calling object. Callback functions are defined in the global section.

' ngSpice_Command(char*)
' Send a valid command (see the control or interactive commands) from caller
' to ngspice.dll. Will be executed immediately (as if in interactive mode).
' Some commands are rejected (e.g. 'plot', because there is no graphics interface).
' Command 'quit' will remove internal data, and then send a notice to caller via ngexit().

' ngGet_Vec_Info(char*)
' receives the name of a vector (may be in the form 'vectorname' or <plotname>.vectorname)
' and returns a pointer to a vector_info struct.
' The caller may then directly assess the vector data (but probably should not modify them).

' ngSpice_Circ(char**)
' sends an array of null-terminated char* to ngspice.dll. Each char* contains a
' single line of a circuit (each line like in an input file **.sp). The last
' entry to char** has to be NULL. Upon receiving the arry, ngspice.dll will
' immediately parse the input and set up the circuit structure (as if received
' the circuit from a file by the 'source' command.

' char* ngSpice_CurPlot();
' returns to the caller a pointer to the name of the current plot

' char** ngSpice_AllPlots()
' returns to the caller a pointer to an array of all plots (by their typename)

' char** ngSpice_AllVecs(char*);
' returns to the caller a pointer to an array of vector names in the plot
' named by the string in the argument.

' Additional basics:
' No memory mallocing and freeing across the interface:
' Memory allocated in ngspice.dll has to be freed in ngspice.dll.
' Memory allocated in the calling program has to be freed only there.

' ngspice.dll should never call exit() directly, but handle either the 'quit'
' request to the caller or an request for exiting upon error,
' done by callback function ngexit().

#include once "crt/long.bi"

extern "C" lib "ngspice"

' Complex numbers.
type ngcomplex_t
  as double cx_real
  as double cx_imag
end type


#ifndef ngspice_BOOL_H
#define ngspice_BOOL_H

type ng_bool as long
#define NG_TRUE  1
#define NG_FALSE 0
#define NG_NO    NG_FALSE
#define NG_YES   NG_TRUE

#endif

#ifndef ngspice_HASH_H
#define ngspice_HASH_H

'#include once "crt/stdint.bi"

#define _NGMALLOC(size_xz)            tmalloc((size_xz))
#define NGMALLOC(n, els)              TMALLOC(els, n)
#define NGREALLOC(ar,n,els)           TREALLOC(els, ar, n)
#define NGFREE(els)                   txfree(els)

type ngdelete as sub (byval param as any ptr)

type ngtable_rec
  as any ptr key
  as any ptr data
  as ngtable_rec ptr next        ' collision list
  as ngtable_rec ptr thread_next ' thread thru entire table
  as ngtable_rec ptr thread_prev ' thread thru entire table
end type
type NGTABLEBOX as ngtable_rec
type NGTABLEPTR as NGTABLEBOX ptr

type _nghashbox as nghashbox

type nghash_func_t         as function(byval hb as _nghashbox ptr, byval param as any ptr) as ulong
type nghash_compare_func_t as function(byval param1 as const any ptr,  byval param2 as const any ptr) as long

type NGHASHBOX
  as NGTABLEPTR ptr hash_table
  as NGTABLEPTR thread                  ' thread of hash table
  as NGTABLEPTR last_entry              ' last entry into hash table
  as NGTABLEPTR enumeratePtr            ' used to enumerate hash table
  as NGTABLEPTR searchPtr               ' used for find again mechanism
  as nghash_compare_func_t compare_func ' the comparison function
  as nghash_func_t hash_func            ' the hash function
  as double growth_factor               ' how much to grow table by
  as long size                          ' the size of the table
  as long max_density                   ' maximum number of entries before growth
  as long num_entries                   ' current number of entries in table
  as long need_resize                   ' amount before we need a resize
  as clong access                       ' used for statistics
  as clong collision                    ' collision times
  as ulong power_of_two   : 8           ' build table as a power of two
  as ulong call_from_free : 8           ' true if in a free calling sequence
  as ulong unique         : 16          ' true if only one unique item in col.
end type
type NGHASHPTR as NGHASHBOX ptr

#endif ' ngspice_HASH_H


#ifndef ngspice_GRID_H
#define ngspice_GRID_H
' Note: SMITHGRID is only a smith grid, SMITH transforms the data
enum
  GRID_NONE
  GRID_LIN
  GRID_LOGLOG
  GRID_XLOG
  GRID_YLOG
  GRID_POLAR
  GRID_SMITH
  GRID_SMITHGRID
end enum
type GRIDTYPE as long

#endif


#ifndef ngspice_WORDLIST_H
#define ngspice_WORDLIST_H
' Doubly linked lists of words.
type wordlist
  as zstring  ptr wl_word
  as wordlist ptr wl_next
  as wordlist ptr wl_prev
end type
#endif

#ifndef ngspice_PLOT_H
#define ngspice_PLOT_H
type ccom as any
type variable as any
type dvec_ as devec

' The information for a particular set of vectors that come from one plot.
type plot
  as zstring ptr  pl_title        ' The title card.
  as zstring ptr  pl_date         ' Date.
  as zstring ptr  pl_name         ' The plot name.
  as zstring ptr  pl_typename     ' Tran1, op2, etc.
  as dvec_ ptr    pl_dvecs        ' The data vectors in this plot.
  as dvec_ ptr    pl_scale        ' The "scale" for the rest of the vectors.
  as plot  ptr    pl_next         ' List of plots.
  as NGHASHPTR    pl_lookup_table ' for quick lookup of vectors
  as wordlist ptr pl_commands     ' Commands to execute for this plot.
  as variable ptr pl_env          ' The 'environment' for this plot.
  as ccom ptr     pl_ccom         ' The ccom struct for this plot.
  as ng_bool      pl_written      ' Some or all of the vecs have been saved.
  as ng_bool      pl_lookup_valid ' vector lookup table valid
  as long         pl_ndims        ' Number of dimensions
end type

#endif

#ifndef ngspice_DVEC_H
#define ngspice_DVEC_H

' Dvec flags.
enum
  VF_REAL      = (1 shl 0) ' The data is real.
  VF_COMPLEX   = (1 shl 1) ' The data is complex.
  VF_ACCUM     = (1 shl 2) ' writedata should save this vector.
  VF_PLOT      = (1 shl 3) ' writedata should incrementally plot it.
  VF_PRINT     = (1 shl 4) ' writedata should print this vector.
  VF_MINGIVEN  = (1 shl 5) ' The v_minsignal value is valid.
  VF_MAXGIVEN  = (1 shl 6) ' The v_maxsignal value is valid.
  VF_PERMANENT = (1 shl 7) ' Don't garbage collect this vector.
end enum
type dvec_flags as long

' Plot types
enum
  PLOT_LIN
  PLOT_COMB
  PLOT_POINT
end enum
type PLOTTYPE as long


' A (possibly multi-dimensional) data vector. 
' The data is represented internally by a 1-d array.
' The number of dimensions and the size of each dimension is recorded,
' along with v_length, the total size of the array.
' If the dimensionality is 0 or 1, v_length is significant instead of v_numdims and v_dims,
' and the vector is handled in the old manner.

#define MAXDIMS 8

type dvec
  as zstring ptr v_name         ' Same as so_vname.
  as long        v_type         ' Same as so_vtype.
  as short       v_flags        ' Flags (a combination of VF_*)
  as double ptr  v_realdata     ' Real data.
  as ngcomplex_t ptr v_compdata ' Complex data.
  as double      v_minsignal    ' Minimum value to plot.
  as double      v_maxsignal    ' Maximum value to plot.
  as GRIDTYPE    v_gridtype     ' One of GRID_*
  as PLOTTYPE    v_plottype     ' One of PLOT_*
  as long        v_length       ' Length of the vector.
  as long        v_rlength      ' How much space we really have.
  as long        v_outindex     ' Index if writedata is building the vector.
  as long        v_linestyle    ' What line style we are using.
  as long        v_color        ' What color we are using.
  as zstring ptr v_defcolor     ' The name of a color to use.
  as long        v_numdims      ' How many dims -- 0 = scalar (len = 1).
  as long        v_dims(MAXDIMS-1)' The actual size in each dimension.
  as plot ptr    v_plot         ' The plot structure (if it has one).
  as dvec ptr    v_next         ' Link for list of plot vectors.
  as dvec ptr    v_link2        ' Extra link for things like print.
  as dvec ptr    v_scale        ' If this has a non-standard scale...
end type

#define isreal(v)    ((v)->v_flags & VF_REAL)
#define iscomplex(v) ((v)->v_flags & VF_COMPLEX)

' list of data vectors being displayed
type dveclist
  as dvec     ptr vector
  as dveclist ptr next
end type

#endif

' vector info obtained from any vector in ngspice *.dll /*.so .
' Allows direct access to the ngspice internal vector structure.
type Vector_Info
  as zstring ptr     v_name     ' Same as so_vname.
  as long            v_type     ' Same as so_vtype.
  as short           v_flags    ' Flags (a combination of VF_*).
  as double ptr      v_realdata ' Real data.
  as ngcomplex_t ptr v_compdata ' Complex data.
  as long            v_length   ' Length of the vector.
end type
type pVector_Info as Vector_Info ptr

type VecValues
  as zstring ptr    name       ' name of a specific vector
  as double         creal      ' actual data value
  as double         cimag      ' actual data value
  as ng_bool        is_scale   ' if 'name' is the scale vector
  as ng_bool        is_complex ' if the data are complex numbers
end type
type pVecValues as VecValues ptr

type VecValuesAll
  as long veccount        ' number of vectors in plot
  as long vecindex        ' index of actual set of vectors. i.e. the number of accepted data points
  as pVecValues ptr vecsa ' values of actual set of vectors, indexed from 0 to veccount - 1
end type
type pVecValuesAll as VecValuesAll ptr

'info for a specific vector
type VecInfo
  as long number         ' number of vector, as postion in the linked list of vectors, starts with 0
  as zstring ptr vecname ' name of the actual vector
  as ng_bool is_real     ' TRUE if the actual vector has real data
  as dvec ptr pDVec       ' a void pointer to struct dvec *d, the actual vector
  as dvec ptr pDVecScale  ' a void pointer to struct dvec *ds, the scale vector
end type
type pVecInfo as VecInfo ptr

' info for the current plot
type VecInfoAll
  ' the plot
  as zstring ptr name
  as zstring ptr title
  as zstring ptr date
  as zstring ptr type
  as long        veccount
  ' the data as an array of vecinfo with length equal to the number of vectors in the plot
  as pVecInfo ptr vecs
end type
type pVecInfoAll as VecInfoAll ptr

'
' callback functions
'
' addresses received from caller with ngSpice_Init() function

' sending output from stdout, stderr to caller
'   string to be sent to caller output
'   identification number of calling ngspice shared lib
'   return pointer received from caller, e.g. pointer to object having sent the request
type SendChar as function(byval sendstr as zstring ptr, byval id as long, byval pUserData as any ptr) as long

' sending simulation status to caller
'   simulation status and value (in percent) to be sent to caller
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type SendStat as function(byval status as zstring ptr, byval id as long, byval pUserData as any ptr) as long

' asking for controlled exit
'   exit status
'   if true: immediate unloading *.dll/*.so, if false: just set flag, unload is done when function has returned
'   if true: exit upon 'quit', if false: exit due to ngspice *.dll /*.so error
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type ControlledExit as function(byval ExitStatus as long, byval ImmediateUnload as ng_bool, byval quit as ng_bool, byval id as long, byval pUserData as any ptr) as long

' send back actual vector data
'   pointer to array of structs containing actual values from all vectors
'   number of structs (one per vector)
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type SendData as function (byval parray as pVecValuesAll, byval nItems as long, byval id as long, byval pUserData as any ptr) as long

' send back initailization vector data
'   pointer to array of structs containing data from all vectors right after initialization
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type SendInitData as function (byval parray as pVecInfoAll, byval id as long, byval pUserData as any ptr) as long

' indicate if background thread is running
'   true if background thread is running
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type BGThreadRunning as function(byval IsRunning as ng_bool, byval id as long, byval pUserData as any ptr) as long

' ask for VSRC EXTERNAL value
'   return voltage value
'   actual time
'   node name
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type GetVSRCData as function(byval voltages as double ptr, byval actualtime as double, byval nodename as zstring ptr, byval id as long, byval pUserData as any ptr) as long

' ask for ISRC EXTERNAL value
'   return current value
'   actual time
'   node name
'   identification number of calling ngspice shared lib
'   return pointer received from caller
type GetISRCData as function (byval current as double ptr, byval actualtime as double, byval nodename as zstring ptr, byval id as long, byval pUserData as any ptr) as long

' ask for new delta time depending on synchronization requirements
'   actual time (ckt->CKTtime)
'   delta time (ckt->CKTdelta)
'   old delta time (olddelta)
'   redostep (as set by ngspice)
'   identification number of calling ngspice shared lib
'   location of call for synchronization in dctran.c
'   return pointer received from caller
type GetSyncData as function (byval actualtime as double, byval delta as double ptr, byval olddeltatime as double, byval redostep as long,byval syncpos as long, byval id as long, byval p as any ptr) as long

' ngspice initialization,
' printfcn: pointer to callback function for reading printf, fprintf
' statfcn: pointer to callback function for the status string and percent value
' ControlledExit: pointer to callback function for setting a 'quit' signal in caller
' SendData: pointer to callback function for returning data values of all current output vectors
' SendInitData: pointer to callback function for returning information of all output vectors just initialized
' BGThreadRunning: pointer to callback function indicating if workrt thread is running
' userData: pointer to user-defined data, will not be modified, but
' handed over back to caller during Callback, e.g. address of calling object */
declare function ngSpice_Init(byval SendCharFunc        as SendChar, _
                              byval SendStatFunc        as SendStat, _
                              byval ControlledExitFunc  as ControlledExit, _
                              byval SendDataFunc        as SendData, _
                              byval SendInitDataFunc    as SendInitData, _
                              byval BGThreadRunningFunc as BGThreadRunning, _
                              byval userData            as any ptr) as long

' initialization of synchronizing functions
' vsrcdat: pointer to callback function for retrieving a voltage source value from caller
' isrcdat: pointer to callback function for retrieving a current source value from caller
' syncdat: pointer to callback function for synchronization
' ident: pointer to integer unique to this shared library (defaults to 0)
' userData: pointer to user-defined data, will not be modified, but
'          handed over back to caller during Callback, e.g. address of calling object.
'          If NULL is sent here, userdata info from ngSpice_Init() will be kept, otherwise
'          userdata will be overridden by new value from here.
declare function ngSpice_Init_Sync(byval GetVSRCDataFunc as GetVSRCData, _
                                   byval GetISRCDatafunc as GetISRCData, _
                                   byval GetSyncDataFunc as GetSyncData, _
                                   byval pID             as long ptr, _
                                   byval userData        as any ptr) as long

' Caller may send ngspice commands to ngspice *.dll / *.so
' Commands are executed immediately
declare function ngSpice_Command(byval cmd as zstring ptr) as long

' get info about a vector
declare function ngGet_Vec_Info(byval vecName as zstring ptr) as pvector_info


' send a circuit to ngspice *.dll / *.so
' The circuit description is a dynamic array of char*.
' Each char* corresponds to a single circuit line.
' The last entry of the array has to be a NULL
declare function ngSpice_Circ(byval ppCircuit as zstring ptr ptr) as long

' return to the caller a pointer to the name of the current plot
declare function ngSpice_CurPlot() as zstring ptr

' return to the caller a pointer to an array of all plots created so far by ngspice *.dll / *.so
declare function ngSpice_AllPlots() as zstring ptr ptr

' return to the caller a pointer to an array of vector names in the plot named by plotname
declare function ngSpice_AllVecs(byval PlotName as zstring ptr) as zstring ptr ptr

' returns NG_TRUE if ngspice is running in a second (background) thread
declare function ngSpice_running() as ng_bool

' set a breakpoint in ngspice
declare function ngSpice_SetBkpt(byval BreakpointTime as double) as ng_bool

end extern

#endif ' __NGSPICE_BI__
Last edited by D.J.Peters on Aug 14, 2016 2:56, edited 3 times in total.
D.J.Peters
Posts: 7099
Joined: May 28, 2005 3:28
Location: Germany

Re: NgSpice a mixed-level/signal circuit simulaton

Postby D.J.Peters » Aug 14, 2016 1:29

A simple test

Joshy
file: test01.bas

Code: Select all

#include once "ngspice.bi"

#define DPRINT(msg) open err for output as #99 : print #99,msg : close #99


function SendChar_CB cdecl (byval SendStr as zstring ptr, byval id as long, byval p as any ptr) as long
  DPRINT("SendChar_CB: id " & id & " str " & *sendstr )
  return 1
end function

function SendStat_CB cdecl (byval status as zstring ptr, byval id as long, byval p as any ptr) as long
  DPRINT("SendStat_CB: id " & id & " status " & *status )
  return 0
end function

function ControlledExit_CB cdecl (byval ExitStatus as long, byval immediateunload as ng_bool, byval quit as ng_bool, byval id as long, byval p as any ptr) as long
  DPRINT("ControlledExit_CB: id " & id & " status " & exitstatus & " immediate unload " & immediateunload & " quit " & quit)
  return 0
end function

function SendData_CB cdecl (byval pArray as pVecValuesAll, byval nItems as long, byval id as long, byval p as any ptr) as long
  'DPRINT("SendData_CB: nItems " & nItems & " VecCount " & pArray->VecCount )
  var v1 = pArray->vecsa[2]->creal
  var v2 = pArray->vecsa[3]->creal
  var T  =pArray->vecsa[5]->creal
  pset (T,v1),1
  pset (T,v2),2
  return 0
end function

function SendInitData_CB cdecl (byval pArray as pVecInfoAll, byval id as long, byval p as any ptr) as long
  DPRINT("SendInitData_CB: id " & id)
  return 0
end function

function BGThreadRunning_CB cdecl (byval IsRunning as ng_bool, byval id as long, byval p as any ptr) as long
  DPRINT("BGThreadRunning_CB: id " & id & " is running " & IsRunning)
  return 0
end function

function GetVSRCData_CB cdecl (byval Voltages as double ptr, byval actualtime as double, byval nodename as zstring ptr, byval id as long, byval p as any ptr) as long
  'DPRINT("GetVSRCData_CB: id " & id & " time " & actualtime)
  if actualtime > 0.005 then
    *voltages = 4.5
  else
    *voltages = 3.5
  end if
  return 0
end function

function GetISRCData_CB cdecl (byval Current as double ptr, byval actualtime as double, byval nodename as zstring ptr, byval id as long, byval p as any ptr) as long
  'DPRINT("GetISRCData_CB: id " & id & " time " & actualtime)
  if actualtime > 0.002 then
    *current = 1.7e-3
  else
    *current = 2.8e-3
  end if
  return 0
end function

function GetSyncData_CB cdecl (byval actualtime as double, byval delta as double ptr, byval olddeltatime as double, byval redostep as long,byval syncpos as long, byval id as long, byval p as any ptr) as long
  'DPRINT("GetSyncData_CB: id " & id & " time " & actualtime)
  if (actualtime < 2e-3) andalso ((actualtime + *delta) > 2e-3) then
    *delta = 2e-3 - actualtime
  end if
  return 0
end function



dim as zstring ptr circuit(...) => { _
  @"titel: circuit via char array" , _
  @"V1 1 0 1" , _
  @"R1 1 2 1" , _
  @"C1 2 0 1 ic=0" , _
  @".tran 1ms 5 uic" , _
  @"V2 11 0 EXTERNAL 2" , _
  @".end" , _
  0}

dim as long id

print"ngSpice_Init = " & ngSpice_Init(@SendChar_CB, _
                                      @SendStat_CB, _
                                      @ControlledExit_CB, _
                                      @SendData_CB, _
                                      @SendInitData_CB, _
                                      @BGThreadRunning_CB, _
                                      0) ' user data

print "ngspice_Init_Sync = " & ngSpice_Init_Sync(@GetVSRCData_CB, _
                                                 @GetISRCData_CB, _
                                                 @GetSyncData_CB, _
                                                 @id,_
                                                 0) ' user data

screenres 640,480
Window ( 0, 5)-( 5, 0)

if ngSpice_Circ(@circuit(0))=0 then
  if ngSpice_Command("bg_run") then
    windowtitle "error: ngSpice_Command('bg_run') !"
  end if
else
  windowtitle "error: ngSpice_Circ(@circuit(0)) !"
end if
windowtitle "press any key for end ..."
sleep
ngSpice_Command("quit")
sleep 2000,1

D.J.Peters
Posts: 7099
Joined: May 28, 2005 3:28
Location: Germany

Re: NgSpice a mixed-level/signal circuit simulaton

Postby D.J.Peters » Aug 14, 2016 3:48

Here are a more complex test.
On end of the simulation it saves the file: "test02.txt" with 17863 menusurements.

Joshy

file: test02.bas

Code: Select all

#include once "ngspice.bi"

dim as zstring ptr circuit(...) => { _
@".TITLE  ADDER - 4 BIT ALL-NAND-GATE BINARY ADDER" , _
@"*** SUBCIRCUIT DEFINITIONS" , _
@".SUBCKT NAND in1 in2 out VDD" , _
@"*   NODES:  INPUT(2), OUTPUT, VCC" , _
@"M1 out   in2 Vdd Vdd p1 W=7.5u L=0.35u pd=13.5u ad=22.5p ps=13.5u as=22.5p" , _
@"M2 net.1 in2   0   0 n1 W=3u   L=0.35u pd=9u    ad=9p    ps=9u    as=9p" , _
@"M3 out   in1 Vdd Vdd p1 W=7.5u L=0.35u pd=13.5u ad=22.5p ps=13.5u as=22.5p" , _
@"M4 out   in1 net.1 0 n1 W=3u   L=0.35u pd=9u    ad=9p    ps=9u    as=9p" , _
@".ENDS NAND" , _
_
@".SUBCKT ONEBIT 1 2 3 4 5 6" , _
@"*   NODES:  INPUT(2), CARRY-IN, OUTPUT, CARRY-OUT, VCC" , _
@"X1   1  2  7  6   NAND" , _
@"X2   1  7  8  6   NAND" , _
@"X3   2  7  9  6   NAND" , _
@"X4   8  9 10  6   NAND" , _
@"X5   3 10 11  6   NAND" , _
@"X6   3 11 12  6   NAND" , _
@"X7  10 11 13  6   NAND" , _
@"X8  12 13  4  6   NAND" , _
@"X9  11  7  5  6   NAND" , _
@".ENDS ONEBIT" , _
_
@".SUBCKT TWOBIT 1 2 3 4 5 6 7 8 9" , _
@"*   NODES:  INPUT - BIT0(2) / BIT1(2), OUTPUT - BIT0 / BIT1," , _
@"*           CARRY-IN, CARRY-OUT, VCC" , _
@"X1   1  2  7  5 10  9   ONEBIT" , _
@"X2   3  4 10  6  8  9   ONEBIT" , _
@".ENDS TWOBIT" , _
_
@".SUBCKT FOURBIT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15" , _
@"*   NODES:  INPUT - BIT0(2) / BIT1(2) / BIT2(2) / BIT3(2)," , _
@"*           OUTPUT - BIT0 / BIT1 / BIT2 / BIT3, CARRY-IN, CARRY-OUT, VCC" , _
@"X1   1  2  3  4  9 10 13 16 15   TWOBIT" , _
@"X2   5  6  7  8 11 12 16 14 15   TWOBIT" , _
@".ENDS FOURBIT" , _
_
@"*** POWER" , _
@"VCC   99  0   DC 3.3V" , _
_
@"*** ALL INPUTS" , _
@"VIN1A  1  0   DC 0 PULSE(0 3 0 5NS 5NS   20NS   50NS)" , _
@"VIN1B  2  0   DC 0 PULSE(0 3 0 5NS 5NS   30NS  100NS)" , _
@"VIN2A  3  0   DC 0 PULSE(0 3 0 5NS 5NS   50NS  200NS)" , _
@"VIN2B  4  0   DC 0 PULSE(0 3 0 5NS 5NS   90NS  400NS)" , _
@"VIN3A  5  0   DC 0 PULSE(0 3 0 5NS 5NS  170NS  800NS)" , _
@"VIN3B  6  0   DC 0 PULSE(0 3 0 5NS 5NS  330NS 1600NS)" , _
@"VIN4A  7  0   DC 0 PULSE(0 3 0 5NS 5NS  650NS 3200NS)" , _
@"VIN4B  8  0   DC 0 PULSE(0 3 0 5NS 5NS 1290NS 6400NS)" , _
_
@"*** DEFINE NOMINAL CIRCUIT" , _
@"X1     1  2  3  4  5  6  7  8  9 10 11 12  0 13 99 FOURBIT" , _
_
@".option noinit acct" , _
@".TRAN 500p 6400NS" , _
@"* save inputs" , _
@".save V(1) V(2) V(3) V(4) V(5) V(6) V(7) V(8)" , _
_
@"* use BSIM3 model with default parameters" , _
@".model n1 nmos level=49 version=3.3.0" , _
@".model p1 pmos level=49 version=3.3.0" , _
@".END", _
  0}

dim shared as boolean ready

function SendChar_CB cdecl (byval SendStr as zstring ptr, byval id as long, byval p as any ptr) as long
  'print *sendstr
  return 1
end function

function SendStat_CB cdecl (byval status as zstring ptr, byval id as long, byval p as any ptr) as long
  if instr(*status,"%") then 
    locate 10,1 : print *status
  else
    if instr(*status, "ready") then ready=true
    print *status
  end if
  return 0
end function

function ControlledExit_CB cdecl (byval ExitStatus as long, byval immediateunload as ng_bool, byval quit as ng_bool, byval id as long, byval p as any ptr) as long
  if quit then ready=true
  return 0
end function

function BGThreadRunning_CB cdecl (byval norunning as ng_bool, byval id as long, byval p as any ptr) as long
  if norunning then ready=true
  return 0
end function

if ngSpice_Init(@SendChar_CB, _
                @SendStat_CB, _
                @ControlledExit_CB, _
                0, _                  ' @SendData_CB, _
                0, _                  ' @SendInitData_CB, _
                @BGThreadRunning_CB, _
                0) then                   ' user data
  print "error: ngSpice_Init() !"
  beep : sleep : end
end if

if ngSpice_Circ(@circuit(0)) then
  print "error: ngSpice_Circ(@circuit(0)) !"
  ngSpice_Command("quit")
  beep : sleep : end
end if

if ngSpice_Command("bg_run") then
  print "error: ngSpice_Command('bg_run') !"
  ngSpice_Command("quit")
  beep : sleep : end
end if

print "running ..."
while ready=false
  sleep 100
wend

print "write test02.txt"
ngSpice_Command("write test02.txt V(2)")
sleep 2000,0

ngSpice_Command("quit")
print "press any key ..."
sleep
greenink
Posts: 199
Joined: Jan 28, 2016 15:45

Re: NgSpice a mixed-level/signal circuit simulaton

Postby greenink » Aug 14, 2016 11:53

Cool, but I'm not doing much with electronics at the moment. However I'll take a look at that version of spice when I have time.
Also there are a few things you can't model, for example:
http://www.kerrywong.com/2014/03/19/bjt-in-reverse-avalanche-mode/
I tried that with a 2sc1815 and it worked well, however if you allow too much current through it will destroy the transistor.
The idea has occurred to me to make a Marx generator using transistors in such a negative dynamic resistance configuration, in place of the spark gap.
https://en.wikipedia.org/wiki/Marx_generator
Edit: I see from the wiki article you could use the transistor in forward avalanche mode too.
I found the 2sc1825 had quite a high reverse avalanche voltage in the 12 to 14 volt range. The forward avalanche would probably be in excess of 100 volts.
aurelVZAB
Posts: 254
Joined: Jul 02, 2008 14:55
Location: Croatia
Contact:

Re: NgSpice a mixed-level/signal circuit simulaton

Postby aurelVZAB » Aug 30, 2016 9:14

Sorry but i must ask
what is a purpose of this lib..
I download from SF ngSpice ..well i dont know but this
spice prog dont have any GUI just a console window app
what a heck is that ?
greenink
Posts: 199
Joined: Jan 28, 2016 15:45

Re: NgSpice a mixed-level/signal circuit simulaton

Postby greenink » Aug 30, 2016 13:19

I guess some people would be willing to type out a wiring list by hand. Most would use a version of spice with a GUI. It is useful to have version of spice without a GUI for automation. For example for filter design.
New version of LTSpice with an updated GUI:
http://www.linear.com/designtools/software/
aurelVZAB
Posts: 254
Joined: Jul 02, 2008 14:55
Location: Croatia
Contact:

Re: NgSpice a mixed-level/signal circuit simulaton

Postby aurelVZAB » Sep 03, 2016 19:01

And what i can do with list ..?
I need something like Circuit Maker or Electronic workbench..

Yes famose LTSpice is very limited thing..
ok i download last release and i discivered that not work on my win7 32 bit machine
gee??
St_W
Posts: 1056
Joined: Feb 11, 2009 14:24
Location: Austria
Contact:

Re: NgSpice a mixed-level/signal circuit simulaton

Postby St_W » Sep 04, 2016 13:05

aurelVZAB wrote:And what i can do with list ..?
I need something like Circuit Maker or Electronic workbench..

SPICE simulates a electronic circuit described by a netlist, so the netlist is the input to the simulator. If you just want to use SPICE get some nice UI (like LTSpice) which simplifies creating netlists by providing graphical circuit design and also can display the output from the simulator as nice graphs.
This library would just be of use if you want to embed circuit simulation functionality into one of your applications. Otherwise I'd use some SPICE derivate that provides a GUI.
For more information about SPICE see https://en.wikipedia.org/wiki/SPICE
btw. LTSpice should work just fine on Win7 32-bit; I don't know what's the problem there...

Return to “Libraries”

Who is online

Users browsing this forum: No registered users and 1 guest