_TOP_MENU

Showing posts with label verilog. Show all posts
Showing posts with label verilog. Show all posts

May 3, 2021

Tips to start a Academic project from scratch to completion


Many students ask , what are the steps to start a academic project , I understand , many people like to learn many things , for example , bus protocols (AHB,AXI, PCIe,USB , etc ) , there are so many of things to learn if someone wishes to do.

Here are the steps to start :

1. Decide a Topic/Subject

This should be based on your future goal and should be align with your current career.

2. Once project topic is decided, you can start collecting the material, like specification, IEEE papers , collect as much as information you can and sort it out , and start reading on the project topic.

3. DO NOT GO for coding directly.

4. Start writing the design specification , we call it micro-architecture

6. First make the input/output interface, findout what are the signals available.

7. Make sure you get good knowledge on it before writing down the specification.

8. Once your top level block diagram is ready, then start thinking about the sub-blocks.

9. This will keep going on , by writing a design-specification, your 60% job is done !! Yeah !!

10.Once specification is done, you can start writing the code.

11.Once code is dome, you can write down the testing logic also.


After step 11, your project would be 100% complete.. 

Few useful links 

Dec 28, 2016

Verilog Code for Round Robin Algorithm


Round Robin algorithm details :
Round Robin algorithm Verilog code :

What is Round Robin algorithm ?

Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing.As the term is generally used, time slices (also known as time quanta) are assigned to each process in equal portions and in circular order, handling all processes without priority (also known as cyclic executive). Round-robin scheduling is simple, easy to implement, and starvation-free. Round-robin scheduling can also be applied to other scheduling problems, such as data packet scheduling in computer networks. It is an operating system concept.



Below is the diagram.




In the real situation, we can have a modified version of round robin.
Below feature can be include while designing a arbiter using round robin.
  1. If there are no requests,  which ever device/master send request, access will be given in next clock cycle.
  2. For some master, priority can be set. 
  3. Programmable delay to get the access if request is present. 

Below is the block diagram for round robin algorithm with 4 request and 4 grant.




Counter will be controlled by a state machine.




Verilog Code for Round Robin Algorithm



Below are the simulation results




In the same way, request/grant can be increased to n number.

Ref - https://en.wikipedia.org/wiki/Round-robin_scheduling

Dec 20, 2016

Verilog code square root of a number


Verilog code to calculate the square root of a number ->

------------------Start of Verilog Code --------------------

`timescale 1ns/100ps

module square_root (
  input [31:0] num,
  output reg[31:0] sqr_root,
  output reg sqr_root_integer
 
  );
 
  integer temp;
  reg [31:0] i;
 
  always @(*) begin
   sqr_root = 'b0;
   sqr_root_integer = 1'b0;
   for (i = 0 ; i < (num/2) ; i = i+1 ) begin
      temp = i*i ;
     if (temp  == num) begin
       sqr_root_integer = 1 ;
       sqr_root = i ;
     end
   end
 end
endmodule

module tb;
  reg [31:0] num_in=0;
  reg clk =0;
  wire integer sqrr;
  wire valid;

  always #1 clk = ~clk;
 
  always @(posedge clk) begin
    num_in = num_in +1 ;
  end
 
  square_root DUT (
  .num(num_in),
  .sqr_root_integer(valid),
  .sqr_root(sqrr)
  );
 
  always@(sqrr)
    if(valid)
    $display("Square root of number %d is %d ", num_in , sqrr);

endmodule


-------------------  End of Code -------------------

Simulation result -> 



Thanks for reading my Blog. 

Parameterized Modules in Verilog


How to pass parameter in verilog design from the top module ?

There are different method to do that , when a module is instantiate with different usage, probably width is one of the parameter which may not be same for all instantiation. For example, There is a FIFO design in which depth of the FIFO is parameterized mean FIFO depth can be set from top module. In below design , we see how to do that.

module fifo (
 parameter DEPTH = 10
)
(
input addr[ ] ,
input data [] ,
....
...
...
);

endmodule


Now we want to use this module in design A.

module A (  input  A ,
                   input B
);

// While instantiating the module, parameter can also be passed to fifo module.
fifo  #( .DEPTH(16) ) inst_fifo
(
.addr(),
.data(),
...
...
)

endmodule

in fifo #( .DEPTH(16)) inst_fifo , we can use parameter also.

fifo  #(.DEPTH(FIFO1_DEPTH)) inst_fifo ..

There are different ways to pass the parameter from top module.

Above parameter can be pass to module in this way also.

fifo  #(FIFO1_DEPTH) inst_fifo ..

In this case , if there are more than 1 parameter then order should be followed.

If a module has localparam , then it can not be override.

We can override the default values, either using defparam or by passing a new set of parameters during instantiation. We call this parameter overriding.

A parameter is defined by Verilog as a constant value declared within the module structure. The value can be used to define a set of attributes for the module which can characterize its behavior as well as its physical representation.

Defined inside a module.
Local scope.
Maybe overridden at instantiation time.
If multiple parameters are defined, they must be overridden in the order they were defined. If an overriding value is not specified, the default parameter declaration values are used.

Formal Definition

Parameters are constants typically used to specify the width of variables and time delays.
Simplified Syntax

parameter identifier = constant_expression ,

identifier = constant_expression ;

defparam hierarchical_path = constant_expression ;

This syntax is specified in the IEEE Standard (1800-2009, for example).

defparam is set during compilation time. 

Sep 27, 2016

Verilog Code for 8-bit ALU

/*
 *inst[3:0]  =  4'h0 => reserved
 *inst[3:0]  =  4'h1 => Addition  
 *inst[3:0]  =  4'h2 => Substraction
 *inst[3:0]  =  4'h3 => Multiply  
 *inst[3:0]  =  4'h4 => division  
 *inst[3:0]  =  4'h5 => shift right
 *inst[3:0]  =  4'h6 => shift left
 *inst[3:0]  =  4'h7 => logical AND
 *inst[3:0]  =  4'h8 => logical OR
 *inst[3:0]  =  4'h9 => Bitwise AND
 *inst[3:0]  =  4'hA => Bitwise OR
 *inst[3:0]  =  4'hB => XOR        
 *inst[3:0]  =  4'hC => Reserved  
 *inst[3:0]  =  4'hD => Reserved  
 *inst[3:0]  =  4'hE => Reserved  
 *inst[3:0]  =  4'hF => Reserved  
 *
 *
 */


`timescale 1ns/100ps

module ALU_8bit (
      input [3:0] inst ,
      input [7:0] op_a,
      input [7:0] op_b,
      output [7:0] op_out
   );


reg [8:0] op_out_int;

assign op_out = op_out_int[7:0];

always @(*) begin
 case (inst)
   4'h1 :  //
       op_out_int = op_a + op_b ;  // can instantiate a adder here
   4'h2 :  //
       op_out_int = op_a - op_b ;
   4'h3 :  //
       op_out_int = op_a * op_b ;
   4'h4 :  //
       op_out_int = op_a / op_b ;
   4'h5 :  //
       op_out_int = op_a >> 1  ;
   4'h6 :  //
       op_out_int = op_a << 1 ;
   4'h7 :  //
       op_out_int = op_a && op_b ;
   4'h8 :  //
       op_out_int = op_a || op_b ;
   4'h9 :  //
       op_out_int = op_a & op_b ;
   4'hA :  //
       op_out_int = op_a | op_b ;
   4'hB :  //
       op_out_int = op_a ^ op_b ;
   default : op_out_int = 'b0;
 endcase
end


endmodule

module tb ;

wire [7:0] ct_a;
wire [7:0] ct_b;
reg [3:0] opcode = 0 ;

integer count =0;

reg clk =0;

always #5 clk = ~clk;

always @(posedge clk)
  count = count + 'h2928_4001;

always @(posedge clk)
  opcode = opcode +1;

assign ct_a = count[9:2];

assign ct_b = count[14:7];



wire [7:0] opout;

ALU_8bit u_dut (  .inst(opcode),
                  .op_a(ct_a),
                  .op_b(ct_b),
                  .op_out(opout) );


always @(*) begin
 #1;
 if (opcode == 1)
   if( opout != (ct_a + ct_b))
     $display("ERROR , Addition not working ");
   else
     $display("Addition : %h + %h = %h" , ct_a, ct_b, opout);
 else if (opcode == 2)
   if( opout != (ct_a - ct_b) )
     $display("ERROR , Subs not working ");
   else
     $display("Substraction : %h - %h = %h" , ct_a, ct_b, opout);
 else if (opcode == 3)
   if( opout != (ct_a * ct_b) )
     $display("ERROR , Multiply not working ");
   else
     $display("Multiply : %h * %h = %h" , ct_a, ct_b, opout);

 else if (opcode == 4)
   if( opout != (ct_a / ct_b) )
     $display("ERROR , division not working ");
   else
     $display("Division : %h / %h = %h" , ct_a, ct_b, opout);

 else if (opcode == 5)
   if( opout != (ct_a >> 1 ) )
     $display("ERROR ,  right shift not working ");
   else
     $display("Right Shift : %h >> 1  = %h" , ct_a, opout);

 else if (opcode == 6)
   if( opout != (ct_a <<  1) )
     $display("ERROR , Left shift not working ");
   else
     $display("Left Shift : %h >> 1 = %h" , ct_a, opout);

 else if (opcode == 7)
   if( opout != (ct_a && ct_b))
     $display("ERROR ,Logical AND not working ");
   else
     $display("Logical AND : %h  && %h = %h" , ct_a, ct_b, opout);

 else if (opcode == 8)
   if( opout != (ct_a || ct_b) )
     $display("ERROR , Logical OR not working ");
   else
     $display("Logical OR : %h || %h = %h" , ct_a, ct_b, opout);

 else if (opcode == 9)
   if( opout != (ct_a & ct_b) )
     $display("ERROR , Bit Wise AND not working ");
   else
     $display("Bit Wise AND : %h & %h = %h" , ct_a, ct_b, opout);

 else if (opcode == 10)
   if( opout != (ct_a | ct_b) )
     $display("ERROR , Bit wise OR not working ");
   else
     $display("Bit Wise OR : %h || %h = %h" , ct_a, ct_b, opout);
 else
  $display("Reserved");

end


`ifdef WAVE
 initial begin
   $recordfile("test.trn");
   $recordvars();
   #1000;
   $finish;
 end
`endif
endmodule

Dec 8, 2015

Selective Signal dumping in VPD VCS


Q. How to dump waveform using command line option in VCS ?


initial begin

$vcspluson();

end

If you are trying to dump VCD format, it is very obvious that this file occupies more space because it contains ASCII format (readable).

If you are trying to dump as VCS's own format called VPD, then you have the following control over that.
$vcdplusfile("my_dump.vpd");
$vcdpluson(<level>, <scope>);
ex: $vcdpluson(0, top.dut.sub);
<level> - default is 0. Dumps all the levels.

$vcdplusoff(<level>, <scope>);
ex: $vcdplusoff(2, top.dut.sub.sub_2);
<level> - default is 0. Switch offs the dump upto the specified
levels.

Q. How to dump waveform in VHDL ?

A. I am searching , if you know please put that in comments.


initial begin
$vcdpluson(0,tb);
$fsdbDumpvars;
$dumpfile("file.vcd");
$dumpvars();
end


Dumping of signal value changes in VCD format can be enabled in verilog by including the $dumpvars system task.

In addition to this method, VCS provides a way to enable VCD dumping at compile time.

This can be achieved by including the following switch  at compile time: "+vcs+dumpvars[+filename]"

For example, consider the following case:

cat test.v

module test;

reg clk;
initial begin
clk = 1'b0;
forever #5 clk = ~clk;
end

initial begin
#100 $finish;
end
endmodule


vcs test.v -V -l logfile -R +vcs+dumpvars+test.vcd

The $dumpvars system task is not specified in the verilog code above. Instead, VCD dumping is enabled with the addition of the compile time switch "+vcs+dumpvars+test.vpd".

The result is equivalent to calling the following system tasks:

$dumpvars;
$dumpfile("test.vpd");

If the filename is not specified (ie. only +vcs+dumpvars is used), then the filename defaults to "verilog.dump".

If both the system task ($dumpvars) and the compile-time switch (+vcs+dumpvars) are specified, then the compile-time switch takes precedence.

No additional verilog code is needed when enabling VCD dumping using the compile time switch.

Put your comments ... if you like it.

Thanks

Aug 27, 2014

Verilog Introduction


Verilog is a HDL language, HDL – Hardware Description Language , which means any digital hardware can be described by verilog language. It is a standard format which simulators and synthesis tools are used to understand digital logic written in Verilog.


For example – D Flop


-----------------------------------D Flip Flop ------------------------
module d_ff (


input d,
input clk, reset,
input en,


output q
);


always @(posedge clk or negedge reset) begin
if(reset)
q <= 1'b0;
else if (en)
q <= d ;
end


endmodule
-------------------------------------------------------------------------


Verilog is not like a 'C' language, it is totally different than other language used in software.


Brief history


Verilog was developed at a time when designers were looking for tools to combine different levels of
simulation. In the early 1980s, there were switch-level simulators, gate-level simulators, functional
simulators (often written ad-hoc in software) and no simple means to combine them. Further, the
more-widespread, traditional programming languages themselves were/are essentially sequential and
thus "semantically challenged" when modelling the concurrency of digital circuitry.
Verilog was created by Phil Moore in 1983-4 at Gateway Design Automation and the first simulator
was written a year later. It borrowed much from the existing languages of the time: the concurrency
aspects may be seen in both Modula and (earlier) Simula; the syntax is deliberately close to that of C;
and the methods for combining different levels of abstraction owe much to Hilo (from Brunnel
University, UK).
In 1989, Gateway Design Automation (and rights to Verilog) were purchased by Cadence who put
Verilog in the public domain in the following year. This move did much to promote the use of Verilog
since other companies were able to develop alternatives tools to those of Cadence which, in turn,
allowed users to adopt Verilog without dependency on a single (primarily workstation-tool) supplier.
In 1992, work began to create an IEEE standard (IEEE-1364) and in December 1995 the final draft
was approved. Thus Verilog has become an international standard - which will further increase its
commercial development and use.
At present, there is standards activity to extend Verilog beyond purely digital circuits. This includes
Verilog-MS for "mixed signal specification" and Verilog-A for "analog" design; the latter was recently
approved (June 1996) by the board of Open Verilog International and is now under consideration by
the IEEE. In addition, work is underway to automate the proof of "equivalence [between] behavioural
and synthesizable specifications" (see the Cambridge web site below) to which Verilog readily lends itself.
While Verilog emerged from developments within private companies, its main rival came from the
American Department of Defence (DoD). In 1981, the DoD sponsored a workshop on hardware
description languages as part of its Very High Speed Integrated Circuits (VHSIC) program, and the
outcome formed a specification for the VHSIC hardware description language (VHDL) in 1983.
Because this was a DoD programme, there were initially restrictions its dissemination, until 1985
when the development was passed on to IEEE whose standard (IEEE 1076) was formally accepted in
1987.
There is, of course, the question as to which language is better. And this, of course, is a hard question
to answer without causing excitement and rebuttals from the marketing departments of the less preferred
language. However, the following points featured in a recent debate in the VHDL and
Verilog news groups.
The main factor is the language syntax − since Verilog is based on C and VHDL is based on ADA:
• Verilog is easier to learn since C is a far simpler language. It also produces more compact code:
easier both to write and to read. Furthermore, the large number of engineers who already know
C (compared to those who know ADA) makes learning and training easier.
• VHDL is very strongly typed, and allows programmer to define their own types although, in
practice, the main types used are either the basic types of the language itself, or those defined by
the IEEE. The benefit is that type checking is performed by the compiler which can reduce
errors; the disadvantage is that changing types must be done explicitly.
Verilog has two clear advantages over VHDL:
• it allows switch-level modelling - which some designers find useful for exploring new circuits
• it ensures that all signals are initialized to "unknown" which ensures that all designers will
produce the necessary logic to initialize their design - the base types in VHDL initialize to zero
and the "hasty" designer may omit a global reset
VHDL has two clear advantages over Verilog:
• it allows the conditional instancing of modules ( if/for ... generate ). This is one of those
features that you do not miss until you have used it once - and then you need it all the time.
Many Verilog users recognize this lack and create personal pre-processing routines it implement
it (which negates some of the advantages of a language standard).
• it provides a simple mechanism (the configure statement) which allows the designer to switch
painlessly between different descriptions of a particular module. The value of this is described
in the next section.
Selecting a design language, however, cannot be done by considering the languages in isolation.
Other factors must include the design environment, the speed of simulation and the ease with which
the designer can test-and-debug the code: the design environment is crucial. Verilog includes the
Programming Language Interface (PLI) which allows dynamic access to the data structure. For the
expert user this gives a degree of control which few simulators (if any) can match. For the tooldesigner
it encourages the development of better design environments with tools such as customized
graphical waveform displays, or C-language routines to dynamically calculate delays for timing
analysis.
Pragmatically, both languages have a large installed base and design-investment − thus a designer
needs to know both. However, the market place is now being won by Verilog: the latest figures
(EDAC’s market research) give Verilog a nearly 2:1 lead over VHDL in tools’ revenue.

NEXT


Verilog Overview main page -
Verilog Overview

Jun 15, 2014

Verilog - Reserved KeyWords

always         starts an  always begin ... end  sequential code block
and            gate primitive, and
assign         parallel continuous assignment
automatic      a function attribute, basically reentrant and recursive
begin          starts a block that ends with  end (no semicolon)
buf            gate primitive, buffer
bufif0         gate primitive, buffer if control==0
bufif1         gate primitive, buffer if control==1
case           starts a case statement
casex          starts a case statement where x matches
casez          starts a case statement where z matches
cell           library, cell identifier, in configuration
cmos           switch primitive, cmos
config         starts a configuration
deassign       stops the corresponding  assign  from accepting new values
default        optional last clause in a case statement
defparam       used to over-ride parameter values
design         top level module, in configuration
disable        a task or block
edge           edge control specifier
else           execute if no previous clause was true
end            end of a block, paired with a begin
endcase        end of a case statement
endconfig      end of a configuration
endfunction    end of a function definition
endgenerate    end of a generate
endmodule      end of a module definition
endprimitive   end of a primitive definition
endspecify     end of a specify
endtable       end of a table definition
endtask        end of a task definition
event          data type
for            starts a for statement
force          starts net or variable assignment
forever        starts a loop statement
fork           begin parallel execution of sequential code
function       starts a function definition
generate       starts a generate block
genvar         defines a generate variable
highz0         drive strength 0
highz1         drive strength 0
if             starts an  if  statement, if(condition) ...
ifnone         state dependent path declaration
incdir         file path for library
include        include file specification
initial        starts an initial begin ... end sequential block
inout          declares a port name to be both input and output
input          declares a port name to be input
instance       specify instance name, in configuration
integer        variable data type, 32 bit integer
join           end of a parallel fork
large          charge strength, 4, of trireg
liblist        library search order for modules, in configuration
library        location of modules, libraries and files
localparam     starts a local parameter statement, not over-ridden
macromodule    same as module with possibly extra meanings  
medium         charge strength, 2, of trireg
module         begin a module definition, also called a cell or component
nand           gate primitive, nand
negedge        event expression, negative edge
nmos           switch primitive, nmos
nor            gate primitive, nor
noshowcancelledno report trailing edge precedes leading edge, in specify
not            gate primitive, not
notif0         gate primitive, not if control==0
notif1         gate primitive, not if control==1
or             gate primitive, or
output         declares a port name to be an output
parameter      starts a parameter statement
pmos           switch primitive, pmos
posedge        event expression, positive edge
primitive      starts the definition of a primitive module
pull0          drive strength 5
pull1          drive strength 5
pulldown       gate primitive
pullup         gate primitive
pulsestyle_oneventglitch detection, in specify
pulsestyle_ondetectglitch detection, immediate change to x, in specify
remos          switch primitive, remos
real           variable data type, implementation defined floating point
realtime       variable data type, floating point time
reg            variable data type, starts a declaration of name(s)
release        release a forced net or variable assignment
repeat         starts a loop statement
rnmos          switch primitive, rnmos
rpmos          switch primitive, rpmos
rtran          bidirectional switch primitive, rtran
rtranif0       bidirectional switch primitive, rtranif0
rtranif1       bidirectional switch primitive, rtranif1
scalared       property of a vector type
showcancelled  report trailing edge precedes leading edge, in specify
signed         type modifier, reg signed
small          charge strength, 1,  of trireg
specify        starts a specify block
specparam      starts a parameter statement for timing delays
strong0        drive strength 6
strong1        drive strength 6
supply0        net data type, and drive strength 7
supply1        net data type, and drive strength 7
table          start a table definition in a primitive
task           starts a task definition
time           variable data type, 64 bit integer
tran           bidirectional switch primitive, tran
tranif0        bidirectional switch primitive, tranif0
tranif1        bidirectional switch primitive, tranif1
tri            net data type
tri0           net data type, connected to VSS
tri1           net data type, connected to VDD
triand         net data type, tri state wired and
trior          net data type, tri state wired or
trireg         register data type associates capacitance to the net
unsigned       type modifier, unsigned
use            library, cell identifier, in configuration
vectored       property of a vector type
wait           starts a wait statement
wand           net data type, wired and
weak0          drive strength 3
weak1          drive strength 3
while          starts a sequential looping statement, while(condition) 
wire           net data type, a basic wire connection
wor            net data type, wired or
xnor           gate primitive, xnor not of exclusive or
xor            gate primitive, xor exclusive or


Jun 1, 2014

Verilog Operators


Verilog HDL operators are same as in C language.

{}   - concatenation 

usage -
reg ab;
reg [1:0] cd ;
reg  [2:0] z ;

always @(*) begin
   z = {cd, ab} ;
end

{3{A} } //  this is equivalent to { A, A, A}
{2 {X, Y}, Z} is equivalent to  {X, Y, X, Y , Z}

+, - , * , /   - arithmetic 

usage -
used in conventional way ..  A = B + C ;

if B and C is 4 -bit , then A should be 5-bit (sum + carry)


%   --  modulus

example - 10 %3  will give remainder 1

> >= < <=    ---  relational

a<b      a less than b
a>b      a greater than b
a<=b    a less than or equal to b

a>=b    a greater than or equal to b

!    --  logical negation

!a  -  invert of a

&&  -- logical and
This is not a bit wise logical AND , bit wise is &

||    --  logical or
This is not a bit wise OR , bit wise is |

==     ---    logical equality
example
a == b a equal to b, result may be unknown


!=      ---   logical inequality
example
a != b a not equal to b, result may be unknown

=== case equality
example
a === b a equal to b, including x and z

!== case inequality
example
a !== b a not equal to b, including x and z

~ bit-wise negation

& bit-wise and


| bit-wise inclusive or


^ bit-wise exclusive or


^~ or ~^ bit-wise equivalence


<<   left shift

>>   right shift


?: conditional


Verilog having syntax restriction for using space , please see below for details.

X & &Y    and X && Y  is  not same ,
X | |Y  and  X |  |Y  is not same.

It is always better to use parenthesis for nested kind of operations.

I think those are the operators which we used normally in RTL coding , there are other operators like string manipulation, but those we don't use in RTL coding.

Please let me know If I missed something here.

NEXT

Pages which you would like to visit -
Verilog Overview
Brain refreshment through Verilog 

Thanks
Rahul J


May 10, 2014

Verilog - System Task


$bitstoreal 
Convert bits into real number.
Syntax
wire [64:1]  abc;
real  num = $bitstoreal(abc);

$countdrivers
The $countdrivers system function is provided to count the number of drivers on a specified net so that bus contention can be identified.

Syntax -
$countdrivers(net, net_is_forced, number_of_01x_drivers, number_of_0_drivers, number_of_1_drivers, number_of_x_drivers);

This system function returns a 0 if there is no more than one driver on the net and returns a 1 otherwise (indicating contention).

net_is_forced returns a "1" if the net is forced and a "0" if the net is not forced
number_of_01x_drivers returns an integer representing the number of drivers that are in a 0, 1, or x state; this represents the total number of drivers on the net that are not forced
number_of_0_drivers returns an integer representing the number of drivers on the net that are in the "0" state
number_of_1_drivers returns an integer representing the number of drivers on the net that are in the "1" state
number_of_x_drivers returns an integer representing the number of drivers on the net that are in the "x" state

$display or $write
These are the main system task routines for displaying information.
Syntax -
$display (Q1,Q2,Q3....Qn );


The contents of string parameters are output literally except when certain escape sequences are inserted to display special characters or specify the display format for a subsequent expression.
It could be inserted in 3 different ways -
1. The special character \ indicates that the character to follow is a literal or non-printable character.
2. The special character % indicates that the next character should be interpreted as a format specification
3. The special character string %% indicates the display of the percent sign character %

\n is the newline character
\t is the tab character
\\ is the \ character
\" is the " character
\o is a character specified in octal digits
%% is the percent character

%h or %H display in hexadecimal format
%d or %D display in decimal format
%o or %O display in octal format
%b or %B display in binary format
%c or %C display in ASCII character format
%v or %V display net signal strength
%m or %M display hierarchical name
%s or %S display as a string
%t or %T display in current time format

%e or %E display `real' in an exponential format
%f or %F display `real' in a decimal format
%g or %G display `real' in exponential or decimal format, whichever format results in the shorter printed output

$strobe
Syntax -
Same as $display.  escape charc and all are same as used in $display.

The difference between $display and $strobe is , $strobe executed at the end of current simulation cycles , which means after all events executed then actual value will be displayed by $strobe.

$monitor
Syntax  - same as $display

The $monitor task provides the ability to monitor and display the values of any variables or expressions specified as parameters to the task.
When you invoke a $monitor task with one or more parameters, the simulator sets up a mechanism whereby each time a variable or an expression in the parameter list changes value–with the exception of the $time, $stime or $realtime system functions–the entire parameter list is displayed at the end of the time step as if reported by the $display task. If two or more parameters change value at the same time, however, only one display is produced that shows the new values.

Note that only one $monitor display list can be active at any one time; however, you can issue a new $monitor task with a new display list any number of times during simulation.

$monitoroff
$monitoron
The $monitoron and $monitoroff tasks control a monitor flag that enables and disables the monitoring, so that you can easily control when monitoring should occur. Use $monitoroff to turn off the flag and disable monitoring. Use $monitoron to turn on the flag so that monitoring is enabled and the most recent call to $monitor can resume its display. A call to $monitoron always produces a display immediately after it is invoked, regardless of whether a value change has taken place; this is used to establish the initial values at the beginning of a monitoring session. By default, the monitor flag is turned on at the beginning of simulation.


$fopen , $fclose , $fwrite, $fdisplay, $fmonitor, $fstrobe 
Each of the four formatted display tasks—$display, $write, $monitor, and $strobe—has a counterpart that writes to specific files as opposed to the log file and standard output. These counterpart tasks—$fdisplay, $fwrite, $fmonitor, and $fstrobe—accept the same type of parameters as the tasks they are based upon, with one exception: The first parameter must be a multichannel descriptor that indicates where to direct the file output.

integer filepp = $fopen("<file_for_writing>");
$fwrite(filepp, " same as $write" );
$fdisplay(filepp, "same as $display");
$fmonitor(filepp, "same as $monitor");
$fstrobe(filepp, "same as strobe" );
$fclose(filepp);



$finish
Syntax:
$finish;
$finish (n);
The $finish system task simply makes the simulator exit and pass control back to the host operating system. If a parameter expression is supplied to this task, then its value determines the diagnostic messages that are printed before the prompt is issued. If no parameter is supplied, then a value of 1 is taken as the default.

0 prints nothing
1 prints simulation time and location
2 prints simulation time, location, and statistics about the memory and CPU time used in simulation

$getpattern


$history
The $history system task prints out a list of all interactive commands that have been entered to a tool.


$input
Syntax - $input("<filename>");
The $input system task allows command input text to come from a named file instead of from the terminal. At the end of the command file the input is automatically switched back to the terminal.

$itor
converts integers to real values (for example, 123 becomes 123.0)

$rtoi
converts real values to integers by truncating the real value (for example, 123.45 becomes 123)

$key
$nokey
$key(“<filename>”);$key;$nokey;
A key file is created by a tool whenever interactive mode is entered for the first time. The key file contains all of the text that has been typed in from the standard input. The file also contains information about asynchronous interrupts.

The $nokey and $key system tasks are used to disable and re-enable output to the key file. An optional file name parameter for $key causes the old key file to be closed, a new file to be created, and output to be directed to the new file.

$list
Syntax -
$list;$list (<name>);

When invoked without a parameter, $list produces a listing of the module, task, function, or named block that is defined as the current scope setting. If an optional parameter is supplied, it must refer to a specific module, task, function or named block, in which case the specified object will be listed.

$log
$nolog
Syntax -
$log(“<filename>”);$log;$nolog;
Tools may create a log file that contains a copy of all the text that is printed to the standard output. The log file may also contain, at the beginning of the file, the host command that was used to run the tool.

The $nolog and $log system tasks are used to disable and re-enable output to the log file. The $nolog task disables output to the log file, while the $log task re-enables the output. An optional file name parameter for $log causes the old file to be closed, a new log file to be created, and output to be directed to the new log file.

$printtimescale
Syntax:

$printtimescale <hierarchical_name>;
When no argument is specified, $printtimescale displays the time unit and precision of the module that is the current scope (as set by $scope).

When an argument is specified, $printtimescale displays the time unit and precision of the module passed to it.

$readmemb
$readmemh
$readmemb("<filename>", <memname>);
$readmemb("<filename>", <memname>, <start_addr>);
$readmemb("<filename>", <memname>, <start_addr>, <finish_addr>);

$readmemh("<filename>", <memname>);$readmemh("<filename>", <memname>, <start_addr>);

$realtime , $time 
The $realtime system function returns a real number time that, like $time, is scaled to the time unit of the module that invoked it.
The $time and $realtime system functions return the current simulation time. The function $time returns a 64 bit value, scaled to the time unit of the module that invoked it. If the time value is a fraction of an integer, $time returns zero. The function $realtime returns a real number that is scaled to the time unit of the module that invoked it.

For example:
`timescale 10 ns / 1 ns
module test;
reg set;
parameter p = 1.55;
initial
begin
$monitor($realtime,,"set=",set);
#p set = 0;
#p set = 1;
end
endmodule
// The output from this example is as follows:
// 0 set=x
// 1.6 set=0

// 3.2 set=1


$realtobits
converts real values to integers by truncating the real value (for example, 123.45 becomes 123)

$reset
$reset_count
$reset_value
The $reset system task enables a tool to be reset to its “Time 0” state so that processing (e.g., simulation) can begin again.
The $reset_count system function keeps track of the number of times the tool is reset. The $reset_value system function returns the value specified by the reset_value parameter argument to the $reset system task. The $reset_value system function is used to communicate information from before a reset of a tool to the time 0 state to after the reset.
The following are some of the simulation methods that you can employ with this system task and these system functions:
• determine the force statements your design needs to operate correctly, reset the simulation time to 0, enter these force statements, and start to simulate again
• reset the simulation time to 0 and apply new stimuli
Verilog HDL LRM 260 • List of System Task and System Function Keywords
• determine that debug system tasks, such as $monitor and $strobe, are keeping track of the correct nets or registers, reset the simulation time to 0, and begin simulation again
The $reset system task tells a tool (for example a simulator) to return the processing of your design to its logical state at time 0. When a tool executes the $reset system task, it takes the following actions to stop the process (e.g., simulation):
• disables all concurrent activity, initiated in either initial and always procedural blocks in the source description or through interactive mode (disables, for example, all force and assign statements, the current $monitor system task, and any other active task)
• cancels all scheduled simulation events
After a simulation tool executes the $reset system task, the simulation is in the following state:
• The simulation time is 0.
• All registers and nets contain their initial values.
• The tool begins to execute the first procedural statements in all initial and always blocks.
Syntax:
$reset;
$reset(<stop_value>);
$reset(<stop_value>,<reset_value>);

$reset(<stop_value>,<reset_value>,<diagnostics_value>);

$restart
$save
$incsave
Three system tasks, $save, $restart, and $incsave, work in conjunction with one another to save the complete state of a tool into a permanent file such that the tool state can be reloaded at a later time and the tool can continue processing where it left off.
Syntax:
$save("<name_of_file>");
$restart("<name_of_file>");

$incsave("<incremental_filename>");

$scale
$scale(<hierarchical_name>);

The $scale function allows the user to take a time value from a module with one time unit to be used in a module with a different time unit. The time value is converted from the time unit of one module to the time unit of the module that invokes $scale.

$scope
$scope("<name>");

The $scope system task allows a particular level of hierarchy to be specified as the interactive scope for identifying objects. This task accepts a single parameter argument that must be the complete hierarchical name of a module, task, function, or named block. The initial setting of the interactive scope is the first top-level module.

$showscopes
$showscopes;$showscopes(n);

The $showscopes system task produces a complete list of modules, tasks, functions, and named blocks that are defined at the current scope level. An optional integer parameter can be given to $showscopes. A nonzero parameter causes all the modules, tasks, functions and named blocks in or below the current hierarchical scope to be listed. No parameter or a zero results in only objects at the current scope level to be listed.

$showvariables
$showvars
$showvars;$showvars(<list_of_variables>);
The $showvars system task produces status information for register and net variables, both scalar and vector. When invoked without parameters, $showvars displays the status of all variables in the current scope. When invoked with a <list_of_variables>, $showvars shows only the status of the specified variables. If the <list_of_variables> includes a bit-select or part-select of a register or net then the status information for all the bits of that register or net are displayed.

The system task $showvariables displays information similar to that of $showvars, but allows more control over the information displayed.

$stop
$stop;
$stop(n);
The $stop system task puts the tool (for example a simulator) into halt mode, issues an interactive command prompt, and passes control to the user. This task takes an optional expression parameter (0, 1, or 2) that determines what type of diagnostic message is printed. The amount of diagnostic messages output increases with the value of the optional parameter passed to $stop.

$timeformat
The $timeformat system task performs the following two functions:
1. It specifies how the %t format specification reports time information for the $write, $display, $strobe, $monitor, $fwrite, $fdisplay, $fstrobe, and $fmonitor system tasks.
2. It specifies the time unit for delays entered interactively.
Syntax:
$timeformat (<units_number>, <precision_number>, <suffix_string>, <minimum_field_width>);

NEXT

You may like to visit below pages -
Source - Verilog LRM 2005 Edition

Refreshing your brain with Verilog


Below are the link for a quick review of verilog language

http://www.tcnj.edu/~hernande/Eng312/TCNJ_Verilog(R)_V05.pdf

Click on main heading for detail information.

Lexical Element 

  • case sensitive 
  • keywords - lowercase
  • comments -  one line comments  start with " // " 
  • comments - more than one line -  start with "/*" and end with "*/"  
  • variable names have to start with an alphabetic character or underscore 
  • system task will start from "$" character 


  • Parameter
  • wire , wor, wand , tri0, tri1, supply0, supply1, trireg, tri, triand, trior  
  • reg
  • integer
  • time
  • real 
  • realtime
  • event
  • task
  • function
  • input , output, input 

  • `define
  • `ifdef , `else , `elsif , `endif
  • `include
  • `resetall
  • `timescale
  • `signed , `unsigned
  • `celldefine, `endcelldefine
  • `unconnected_drive pull0 | pull1
  • `nounconnected_drive 
  • `remove_netname , `noremove_netnames
  • `protect , `endprotect 

  • $display
  • $monitor
  • $strobe
  • $write
  • $fwrite
  • $fdisplay
  • $fmonitor
  • $time
  • $realtime
  • $finish
  • $showvars
  • $scale
  • $scope
  • $showscopes
  • $stop
  • $setup
  • $hold
  • $setuphold
  • $readmemb
  • $readmemh
  • $getpattern




and

always

assign

attribute

begin

buf

bufif0

bufif1
case
cmos
deassign
default
defparam
disable
else
endattribute
end
endcase
endfunction
endprimitive
endmodule
endtable
endtask
event
for
force
forever
fork
function
highz0
highz1
if
initial
inout
input
integer
join
large
medium
module
nand
negedge
nor
not
notif0
notif1
nmos
or
output
parameter
pmos
posedge
primitive
pulldown
pullup
pull0
pull1
rcmos
reg
release
repeat
rnmos
rpmos
rtran
rtranif0
rtranif1
scalared
small
specify
specparam
strong0
strong1
supply0
supply1
table
task
tran
tranif0
tranif1
time
tri
triand
trior
trireg
tri0
tri1
vectored
wait
wand
weak0
weak1
while
wire
wor









Source - http://www.verilog.org/verilog-ams/htmlpages/public-docs/lrm/2.3/VAMS-LRM-2-3.pdf




Parallel statement -    
fork ...... join

Conditional statement - 
if ..... else 
if .... else if .... else 
case 
casez
casex

Looping statement 
forever 
for ( ) 
repeat () 
while () 


Continuous Assignment  
wire abc = 5'd10 ;
assign abc = 5'd10 ; 
assign a = b ; 

Procedural Assignment 
initial 
always 
task
function

Blocking Assignment 
a = b ;
b = c ; 
c = a ; 

Non-Blocking Assignment 
a <= b ;
b <= c ;
c <= a ;
$finish 
$stop
$monitoron
$monitoroff
$dumpon
$dumpoff
$dumpfile
$dumplimit
$dumpflush
$dumpvars
$dumpall
$reset
$random
$realtobits
$bitstoreal 
$rtoi
$itor


$display 
$monitor 
$strobe 
$fdisply
$fmonitor
$fstrobe

$display(" Counting start - %AB " , count); 

AB = d  -> display in decimal
AB = h  -> display in hex 
AB = b  -> display in binary 
AB = o  -> display in octal
AB = c  -> display in  ACSII 
AB = v  -> display  net signal strength 
AB = s  -> display as string
AB = t  -> display in current time format 
AB = m  -> display hierarchical name 
AB = e  -> display real in scientific form
AB = f  -> display real in decimal form
AB = g  -> display real in shortest form

Waveform dump using $dump system task -
Syntax  -
$dumpfile(<filename>);
$dumpvars(<levels> <,<module|var>>* );
$dumpoff;
$dumpon;
$dumpall;
$dumplimit(<filesize>);
$dumpflush;
The $dumpfile system task specifies the name of the value change dump file.
The $dumpvars system task specifies the variables whose changing values a tool records in the value change dump file. The $dumpvars when invoked with no arguments dumps all variables in the design.
The $dumpoff system task stops a tool from recording value changes in the value change dump file.
The $dumpon system task allows a tool to resume recording value changes in the value change dump file.
The $dumpall system task creates a checkpoint that shows the current value of all variables being recorded in the value change dump file.
The $dumplimit system task sets the size of the value change dump file.
The $dumpflush system task empties the dump file buffer and ensures that all the data in that buffer is stored in the value change dump file.

initial begin
$dumpvar(<file>.wave);
$dumpvars();  // dump all
end

Thanks for visiting my blog.

Verilog Overview main page -
Verilog Overview

Mar 24, 2014

Verilog Design Style

Verilog HDL allow users to go for design either bottom up or top down.

Bottom up - 
The traditional method of electronic design is bottom-up. Each design is performed at the gate-level using the standard gates (refer to the Digital Section for more details). With the increasing complexity of new designs this approach is nearly impossible to maintain.


Top Down -
The desired design-style of all designers is the top-down one. A real top-down design allows early testing, easy change of different technologies, a structured system design and offers many other advantages.

With increasing complexity in the design and increasing gate count , it is impossible to keep one pure approach through out the development of a design , people are following a mix of both approach.

From my experience , First I used Top down approach and defined all the interface at top level and  then define the sub block in the design. Once architecture is finalize at broad level then one can start exploring the individual blocks and those blocks can be designed with Bottom up approach.

It is a common approach to build the logic, you need to prepare micro-architecture and architecture document before coding. Coding you can do either with verilog or with VHDL.

Verilog - Statements


Parallel statement -    
fork ...... join

Conditional statement - 
if ..... else 
if .... else if .... else 
case 
casez
casex


Looping statement 
forever 
for ( ) 
repeat () 
while () 


Continuous Assignment  
wire abc = 5'd10 ;
assign abc = 5'd10 ; 
assign a = b ; 

Procedural Assignment 
initial 
always 
task
function

Blocking Assignment 
a = b ;
b = c ; 
c = a ; 

Non-Blocking Assignment 
a <= b ;
b <= c ;


c <= a ;


Mar 22, 2014

Verilog - Data Types


Verilog HDL consists of 4 basic values -
0 - Logic zero
1 - Logic one
x - unknown value
z -high-impedance state

value z and x are same, notable exception are the primitives which can pass the z value.

Nets and Registers 
The net data types represent the physical connections, a net does not store a value (except trireg net).
Register type will store the value from assignment.

Declaring reg and net types -

reg [N-1:0] <reg_name1> , <reg_name2> ;

declaring N-bit register named reg_name1 and reg_name2

wire [N-1:0] <wire_name1> , <wire_name2>;

declaring N-bit wire named wire_name1 and wire_name2

tri [N-1:0] tri_name ;
A tri state tri_name signal with N-bit

One can declare integer , time , real type of variables.

Declaration of memory -

reg [3:0] mem [4:0] ;

This will create memory of 5 registers of 4-bit each.


Parameters 

Parameters are not reg type or wire type, all parameter declaration is a constant.
syntax to declare parameter -
parameter abc = 1;
parameter x =10, y = 12;
parameter z = expression (abc) ;   // abc should be a constant value

NEXT

Pages which you would like to visit -
Verilog Overview
Brain refreshment through Verilog 

Thanks for visiting my Blog.
Rahul Jain

Mar 12, 2014

How simulator executes blocking and non-blocking statement in Verilog


We all know that there are blocking statements and non-blocking statements ,  If I ask what is blocking and what is non-blocking , the first answer I used to get is , blocking used in combinational circuits and non-blocking used in sequential circuit.

People makes mistake while saying above statement , it's not definition.

below is the definition of blocking statement -

A blocking procedural assignment statement must be executed before the execution of next statement in a sequential block. But a blocking procedural assignment statement does not prevent the execution of statement that follow it in parallel block.

What does it mean ..  ??

In simple way , in blocking statement , simulation tool evaluates RHS and assigned it to LHS before moving to next statement.
but when you are using fork...join  , this is parallel execution and simulation tool will start evaluation of all statements in fork ...join with same time stamp.

If this question asked during interview, then don't make a mistake by saying "=" is blocking statement and "<=" is non-blocking statement.


Non-Blocking statement - 
The non-blocking procedural assignment allows you to schedule assignments without blocking the procedural flow. You can use the non-blocking procedural statement whenever you want to make several register assignments within the same time step without regard to order or dependence upon each other.

It means , in a procedural block, all non-blocking statement will executes at same time stamp , simulation tool will start evaluating all non-blocking statement at same time stamp but assignment will happen at the end of current time stamp.

Now, the question is , why do we say combinational logic uses blocking statement and sequential logic uses non-blocking statement ??

Imagine you have combinational logic , 2 AND gate connected back to back , if something happen on AND1 gate then after gate delay, assignment will happen on AND2 gate , and this event is not depend on any clock or other signal, its continuous assignment and  whenever AND1 gate input change , AND2 gate output will changed.

if you write this in non-blocking style, then this will not be correct and old value of AND2 gate will propagate to sequential circuit in simulation , but in actual hardware , correct value of AND2 gate will propagated.
So there is mismatch between simulation and actual hardware and to stop this, we follow the guideline which say combinational circuit should use blocking type of statement.

If you have used non-blocking type of statement in combinational logic, you must get lint warnings in log. Every designer should check lint log carefully.

How the simulator evaluates non-blocking procedural assignments

When the simulator encounters a non-blocking procedural assignment, the simulator evaluates and executes the non-blocking procedural assignment in two steps.
1. The simulator evaluates the right-hand side and schedules the assignment of the new value to take place at a time specified by a procedural timing control.
2. At the end of the time step, in which the given delay has expired or the appropriate event has taken place, the simulator executes the assignment by assigning the value to the left-hand side.


How the Simulator Processes Blocking and Non-Blocking Procedural Assignments

For each time slot during simulation, blocking and non-blocking procedural assignments are processed in the following way:
1. Evaluate the right-hand side of all assignment statements in the current time slot.
2. Execute all blocking procedural assignments. At the same time, all non-blocking procedural assignments are set aside for processing.
3. Execute all non-blocking procedural assignments that have no timing controls.
4. Check for procedures that have timing controls and execute if timing control is set for the current time unit.
5. Advance the simulation clock.

Very good article to understand more --
http://web.mit.edu/6.111/www/f2007/handouts/L06.pdf

Other Article -
Digital Design .... 

Posted by Rahul Jain , Technical Lead at Synapse Design, Bangalore


Mar 4, 2014

Verilog - Lexical Element


Lexical --  it means related to the language, here will describe in more detail about the lexical elements in verilog.

Convention Overview 

This is important because this will let you know how to use verilog construct in RTL coding. Verilog is not much high rule constraint based language ,but to use it , you need to know few basic thing mentioned below.

  • operator
  • whitespace
  • comment
  • number
  • string
  • identifier
  • keyword

operator 
Operators are single, double or triple character sequence and used in expression.


Urinary operators appear to be left of their operand.
Binary operators appear between their operands.
A ternary operator has two operator character that separate three operands.

white space and comments 
white space can contain char like space, tab, newlines ,etc
comments , one line comment will start from  //
multiple line comments will start from /* and end with */

number
Constant number can be specified in decimal, hexadecimal, octal or binary format.

exp -
23   // decimal number
'b10101  // binary number
'd23   // decimal number
'hF3  // hex number
'o23 // octal number

This can be divided into sized and unsized number .. sized number will be like 5'h1F  // 5 -bit number

string 
string is a sequence of character enclosed by double quotes and all must be in a single line.
Verilog treats strings used as operand in expression and assignment as a sequence of 8-bit ASCII value.
string manipulation is also possible in verilog but all will be done after converting into ASCII value.

Will not go in much details as we normally don't use those in RTL coding.
Special character in string -

\n  - new line
\t  - tab charc
\\ \character
\" "character
%% %character

identifier 
first character must not be a digit or $ ; it can be a letter or an underscore
lowercase , uppercase letters are considered to be different.

Escaped Identifiers 
Escaped identifiers start with the backslash character (\) and provide a means of including any of the printable ASCII characters in an identifier (the decimal values 33 through 126, or 21 through 7E in hexadecimal).


keyword 
Keywords are predefined non-escaped identifiers that are used to define the language construct.
Any keyword having escape character in starting , is not considered as Verilog Keyword.
system task includes in keywords.

Text Substitution 
For re-usability of RTL code , one can use `define in RTL and use Macro in RTL instead of constant number.
all define/parameter can be override or defined in a separate file which can used in configuration of design.

NEXT

For more information, visit below page.
Verilog - Compiler Directive

Verilog Overview main page -
Verilog Overview


Thanks for your time.

Mar 2, 2014

Verilog Overview



  • Introduction
  • Design Style
  • Language description
    • Module
    • Lexical conventions
    • Data types
    • Operators
  • Modeling Style
    • Gate Level Modeling
    • Data Flow modeling
    • Behavioral Modeling
  • Other things in Verilog
  • Simulation and testbench