Vous êtes sur la page 1sur 22

Circuits Electroniques-FPGA-Introduction au Verilog

Circuits Logigques Programmables -


Introduction to Verilog
Les circuits Logiques Programmables ou Circuits reconfigurables comme les FPGA « Field Programmable
Gate Arrays » sont des circuits intégrés conçus pour être configurés ou modifiés à volonté par
l’utilisateur. Ils sont constitués des blocs configurables, des ressources d’interconnexion, et des blocs
matériels dédiés comme les mémoires, les registres, les DSPs, les processeurs, les multiplieurs, etc. Les
FPGAs sont configurés à l’aide d’un programme appelé « bitstream ». C’est ce bitsream qui donne au
FPGA la configuration matérielle voulue. Le bitstream est produit par un outil logiciel appelé
« Synthetiseur », à partir d’une description du circuit en langage de description matérielle.

Les Circuits reconfigurables sont donc des circuits digitaux dont les éléments logiques les constituant
peuvent être configurés pour réaliser n’importe quel circuit numérique. Du fait qu’ils soient
reconfigurables, permettent aux FPGAs d’être utilisés dans des applications très larges telles que :

 Le prototypage rapide : Les ASICs modernes sont si complexes que l’effort de conception et de
fabrication peut être très long. Les FPGA peuvent donc être utilisés pour disposer d’un prototype qui
est sensé se comporter comme le produit final. On peut donc faire tout un ensemble des tests et
vérification sur ce prototype avant de se lancer dans la mise en œuvre de l’ASIC.
 Applications à faible volume du marché: Pour les applications dont le volume du marché est
faible, le développement d’un ASIC n’est pas rentable, et si ces applications nécessitent d’être
implémentées en hardware, alors les FPGAs peuvent valablement remplacés les ASICs comme
plateforme matérielle. Le faible coût de développement des applications sur FPGAs ainsi que le petit
temps d’arrivée sur le marché, font que les FPGAs se retrouvent carrément dans les produits finaux.
 Plateforme pour la conception et la vérification des nouveaux algorithmes.
 L’évolution actuelle de FPGA permettant d’embarquer cœurs des processeurs, des mémoires,
des multiplieurs et autres accélérateurs rend possible la conception des SoCs dans les FPGAs, on parle
de Programmable System-on-Chip « PSoC ».

Du point de vue de leur constitution, les FPGAs sont constitués (Modèle Xilinx Fig. 2.16 et 2.17) de
composants suivants :

 Blocs Logiques Configurables « CLB », lesquels sont constitués des Look Up Tables « LUT », des
éléments séquentiels (registres) et autres logiques combinatoires. Les configurations des LUTs
sont stockées dans des mémoires SRAM pendant le fonctionnement. Ces mémoires perdent
leurs données quand elles ne sont plus alimentées, il est donc nécessaire de charger la
configuration du FPGA à chaque mise sous tension.

Kuti Lusala Page 1


Circuits Electroniques-FPGA-Introduction au Verilog

Figure 2.1 Simple CLB

 Des interfaces entrées-sorties (I/O)


 Des matrices d’interconnexion

Certains composants sont optionnels, comme par exemple des mémoires en durs, des processeurs en
durs, des multiplieurs, des DSPs, etc. Cependant, la plupart des FPGAs actuels incluent ces ressources
pour réaliser des systèmes électroniques entiers à l’échelle d’un seul circuit intégré.

Figure 2.2. Architecture FPGA

Kuti Lusala Page 2


Circuits Electroniques-FPGA-Introduction au Verilog

Un Look Up Table, en fonction du nombre de ces entrées, permettent de réaliser toutes sortes des
fonctions logiques combinatoires. Les FPGA actuels ont des Look Up Table avec 5 ou 6 entrées. A titre
d’exemple, réalisons à l’aide d’un Look Up Table la fonction logique ci-dessous :

𝑌 = 𝐴 .𝐵 + 𝐶

Le circuit logique réalisant la fonction ci-dessous est direct :

Le processus de conception d’un système électronique sur une plateforme FPGA suit les étapes ci-
dessous :

 Description du circuit en Langage de description matérielle (Verilog, VHDL, System Verilog, etc)
ou une saisie schématique du circuit.
 Synthèse : qui est l’étape qui permet de transformer le code HDL en « netlist » schématique,
c'est-à-dire la représentation décrivant le schéma du circuit à partir de la description en langage
matérielle. Il s’agit là d’un ensemble des portes logiques et de leur interconnexion.
 Implémentation : regroupe les différentes étapes ci-dessous :
o Translate: permet, à partir de la netlist issue de la synthèse, de convertir les portes
logiques en primitives du fabricant.
o Map : Mappe le circuit logique obtenu vers les primitives du FPGA, tout en vérifiant les
règles DRC
o Place & Route : Place et effectue le routage du design dans le FPGA
 Génération du Bitstream
 Programmation du FPGA

Kuti Lusala Page 3


Circuits Electroniques-FPGA-Introduction au Verilog

Kuti Lusala Page 4


Circuits Electroniques-FPGA-Introduction au Verilog

Introduction au Verilog
In the days of lore, electronic circuits, regardless of their complexity, had to be designed through
schematics. These were complex, hard to simulate and generally error-prone. With the introduction of
Hardware Description Languages (HDL), a specification was established to allow circuits to be concisely
and accurately modelled, thus giving designers a way of providing not only an exact description of the
circuit, but also automatic design verification tools. Verilog is one such HDL, popular in the electronics
industry.

Now, this is important: Verilog is not a programming language! Verilog is a circuit description that just
happens to look like a programming language. The difference is subtle but crucial. In programming
languages, the processor executes a number of instructions sequentially. In Verilog, there are no
“operations”, only connections between gates and modules. Therefore, in Verilog all connections are in
parallel and can only be made sequential by inserting registers or special structures.

So, Verilog is based on modules that are connected to each other, with basic logic gates as the most
fundamental modules. A Verilog description of a circuit is contained in a module, which can instantiate
one or more other modules. A module is characterized by its ports (inputs/outputs) which allow
communications with other modules. A module is defined like this:
module my_cool_module(
input [3:0] my_first_input,
input [7:0] my_second_input,

output my_cute_output
);

// Do stuff.
endmodule

So, what did we do there? We defined a module, that we call “my_cool_module” that has two inputs and
one output. The first input is 4 bits wide, the second is 8 bits wide, defined from bit 7 down to 0 in order
to match the standard bit-ordering convention that has the LSB being bit 0. While it is possible to change
the order, please don’t! When no bits are specified, like in the output, a one-bit wide signal is assumed.

Suppose that by some strange accident module actually does something useful and we would like to use
it. Here’s how to instantiate it in a higher-level module:
module my_toplevel();
wire [3:0] input_connection1;
wire [7:0] input_connection2;
wire output_connection1;
wire output_connection2;
my_cool_module local_instantiation_name1 (
.my_first_input (input_connection1),
.my_second_input (input_connection2),
.my_cute_output (output_connection1)
);
my_cool_module local_instantiation_name2 (
.my_first_input (input_connection1),
.my_second_input (input_connection2),
.my_cute_output (output_connection2)
);
endmodule

Kuti Lusala Page 5


Circuits Electroniques-FPGA-Introduction au Verilog

And this is what that represents:

Okay, to instantiate a module we need to say what module, then give it a local name. Instance names
must be unique and are case-sensitive. Next we need to connect the input/output ports, which is done
via the ‘.’ operator. Use ‘.’ followed by the port name in the target module, and connect that to the local
wire in the parentheses.

Kuti Lusala Page 6


Circuits Electroniques-FPGA-Introduction au Verilog

Basic operators
Okay, you may be thinking that if you need to instantiate all gates individually it could take a while to get
anything done! That’s why verilog has operators, which are like shortcuts to standard modules that the
tools automatically replace when run. There are quite a few operators around:

Operator Type Symbol Operation Performed


Arithmetic * Multiply
/ Division
+ Add
- Subtract
% Modulus
+ Unary plus
- Unary minus
Logical ! Logical negation
&& Logical and
|| Logical or
Relational > Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Equality == Equality
!= inequality
Reduction ~ Bitwise negation
& and
~& nand
| or
~| nor
^ xor
^~ xnor
~^ xnor
Shift >> Right shift
<< Left shift
Concatenation {} Concatenation
Conditional ? conditional

On top of that, you also get the assignment, which sets a wire equal to a value or another wire:
assign a = b;

Number formats
Obviously, numbers are important in verilog, and as such they are defined in a special way. When
specifying a number, you must specify their width (the number of bits that is used to represent that
number), and their radix (what base the number is in).

In verilog, you must first specify the width, then a separator symbol `’`, followed by the radix, then the
number itself, in the form <size>'<radix><value>. The radix can be decimal, binary, octal,
hexadecimal and others. Any underscore ‘_’ in the number is ignored, and can be used for cosmetic
purposes.

Kuti Lusala Page 7


Circuits Electroniques-FPGA-Introduction au Verilog

So, 4'b1001 represents the decimal number 9 and is stored on 4 bits, 10'd1023 represents a 10-bit
decimal number and 32'hDEAD_BEEF is a fancy hexadecimal number. Hex is fun! :P

Gate-Level Modelling
This consists in describing the circuit by instantiating primitive logic gates such as and, nand, or, nor, xor,
etc. These primitive gates are predefined in Verilog and are instantiated like modules, however there is
no need for a module definition of them. For example:

and and_gate (OUT, IN1, IN2) instantiates a and gate with two inputs (IN1, IN2) and an output OUT:

or or_gate (OUT, IN1, IN2) instantiates a and gate with two inputs (IN1, IN2) and an output OUT:

Each gate is characterized by its truth table, its logic symbol and its Verilog primitive.

Dataflow Modelling
The gate-level modelling is interesting for very simple and small designs, when the complexity of the
design is still low; when the number of gates increases, it becomes painful or impossible to describe the
design with the gate-level modelling. Dataflow modelling allows designing circuit in terms of transactions
of data (data flow) between registers. In this approach, one focuses to how data are processed rather
instantiating individuals gates.

The continuous assignment ‘assign’ construct


Dataflow modelling uses continuous assignment (assign) statements and basic operators described
above when expressing how data is processed. Continuous assignment allows describing combinatorial
circuits in which the output of the circuit only depends on the inputs. For example, describing the above
and gate with continuous assignments will be done like this:
module and_gate(input IN1, input IN2, output OUT);
assign OUT = IN1 & IN2;
endmodule
The assign statement can be applied to any net (wire) declared in the design. For example:

wire my_wire;

assign my_wire = IN1 & IN2;

Kuti Lusala Page 8


Circuits Electroniques-FPGA-Introduction au Verilog

Behavioural Modelling
This is the highest level of abstraction when describing a digital circuit. It allows the functionality of the
circuit to be described algorithmically, implicitly inserting the necessary logic. Behaviour modelling is
used to model both sequential and combinational circuits. Verilog HDL has plenty of behavioural
constructs, here are just two of them: the ‘always’ and the ‘initial’ constructs, which allow structured
procedures in Verilog.

The ‘always’ construct


Assembling different modules in the way outlined in gate-level and dataflow modelling will result in a
flurry of activity followed by the output results. No clock, no fuss, the output is obtained as soon as it
propagates through the electronics. Here is an example of such a circuit:
module add(input [3:0] a, input [3:0] b, output [4:0] out);
assign out = a + b;
endmodule

This is exactly the same as:


module add(input [3:0] a, input [3:0] b, output reg [4:0] out);
always @ (*)
begin
out <= a + b;
end
endmodule

So what happened here? The output is now typed ‘reg’, which means it is modified inside an always
block (it is not necessarily a register, and is not in this case). Then we have an always block that “runs”
what’s inside it when whatever is in its sensitivity list (the parentheses) changes. Since we have a star
here, this will occur whenever any of the signals in the module change. All we do when that happens is
to set out to be equal to the sum of a and b. ‘<=’ is a non-blocking assignment, whereas ‘=’ is a blocking
assignment:

three <= 4'd1 + 4'd2; three = 4'd1 + 4'd2;


four <= three + 4'b1; four = three + 4'b1;

These are done in parallel, so These are done sequentially, so


four = <old value of ‘three’> + 1 = 1 four = <’three’> + 1 = 4.
(and = 4 only comes later, during a following cycle).

You might also like to play with a clock. In this case, we need to make the sensitivity list of the always
block reflect this:
module add(input clk, input reset, input [3:0] a, input [3:0] b, output reg [4:0] out);
always @ (posedge clk, posedge reset)
if(reset) out <= 5'b0;
else out <= a + b;
endmodule

Here, ‘out’ is only set after a positive edge of the ‘clk’ signal. And in this case, ‘out’ is the output of a

Kuti Lusala Page 9


Circuits Electroniques-FPGA-Introduction au Verilog

physical register. Also, since this ain’t programming, we like to have a ‘reset’ signal that puts everything
back into a known state. So the always construct is used to describe cyclic behaviour.

The ‘initial’ construct


This describes behavior occurring once either in simulation or when initializing some components such as
memories. All statements inside an initial statement constitute an initial block. An initial block
starts at time 0, executes exactly once, and then does not execute again. If there are multiple initial
blocks, each block starts to execute concurrently at time 0. Each block finishes execution independently
of other blocks. Be wary of using initial outside of a testbench, since such constructs are generally not
synthesizable, and it is therefore often better to use a ‘reset’ signal instead.

An example of using initial block for generating stimuli during simulation is given below:
initial begin
a = 0; b = 0; c = 0; #10;
c = 1; #20;
b = 1; c = 0; #10;
end

In this example, at the start of simulation the initial statement assigns value 0, 0, and 0 to a, b and c
respectively, then waits 10 time units. It then assigns the value 0, 0, and 1 to a, b and c, waits 20 time
units, and so forth. The time unit used is defined via the `pragma timescale 1ns/1ps directive (in this
case yielding abase time unit of 1ns, with a simulation internal resolution of 1ps).

There’s more
Okay, that was a very very fast and superficial introduction to Verilog, that doesn’t even begin to cover
what you will actually need. For that, you should see the reference book and visit online tutorial sites.

Kuti Lusala Page 10


Circuits Electroniques-FPGA-Introduction au Verilog

Simulation
When developing something, it is nice to be able to debug it. In order to perform the simulation, we
need a verilog simulator. Here we will use ModelSim to simulate a simple counter:

clk LED
+
reset
1

1. Copy the tp1.v and modelsim_toplevel.v files to a new empty directory (with no spaces in the
name!).

2. Start Modelsim ALTERA STARTER EDITION, which can be found in Program files -> Altera ->
Modelsim altera starter edition:

3. Create a new project

Kuti Lusala Page 11


Circuits Electroniques-FPGA-Introduction au Verilog

a. FileNewProject

b. Enter in the Create Project dialog box, tp1 as project name and select the directory
where the provided files are stored. Do not modify the remaining fields and click OK.

4. Now, add files to the project:

5. Click OK, you should now see the following window:

6. Double click on each file and try to understand the design, if you have some problem, feel free to
call us.

Kuti Lusala Page 12


Circuits Electroniques-FPGA-Introduction au Verilog

7. Compile all files with the button “Compile all”:

There should be no errors:

8. Start the simulation:

a. SimulateStart Simulation

b. Expand “work” and select the “top” module:

c. Click OK. Once the tool is ready, right-click on top, and choose addto waveAll signals
in region:

d. Open the wave window that pops up.

9. Now, in the command bar at the bottom, type in “run 500ns”. Watch the waves and explore the
tool for a while!

Kuti Lusala Page 13


Circuits Electroniques-FPGA-Introduction au Verilog

Synthesis
In the last section, you performed a behavioural simulation, in that the ModelSim simulator interpreted
your verilog code directly, and displayed the results. Sadly, this cannot run on any physical device in this
way. In order to design an integrated circuit chip (ASIC – Application-specific Integrated Circuit) or to
program an FPGA (Field-programmable Gate Array) as will be done here, your verilog code has to be
processed in a number of steps.

For FPGAs, these steps are:

1. Analysis (checks for syntax errors in your verilog)


2. Synthesis (converts the verilog to a netlist in the tool’s internal format)
3. Mapping (transforms ‘standard’ gate models, to physical elements found on the device)
4. Place&Route (selects which physical elements are to be used on the device, and calculates the
signal routing between them)
5. Assembler (creates a file that can be used to program the FPGA)

These steps are performed by a synthesis tool, which is Quartus in the case of Altera FPGAs (in that
software, steps 3 and 4 are combined into a single “Fitter” step). For ASIC design, see the ELEC2570
course ;-).

So, let’s do that!

1. Locate Quartus on your system, open it up. You will be greeted by a friendly blue window asking
you what you wish to do next. Click on “Create a new Project”:

2. Click next through the introduction page.

3. Give the project a nice name, and save it to a directory that contains no spaces. Anywhere. So
“My Documents” is probably a bad idea. Lastly, the name of the top module should be set to the

Kuti Lusala Page 14


Circuits Electroniques-FPGA-Introduction au Verilog

name of the verilog module you want to be the main one:

4. On the next screen, add the single file tp1.v. Not the modelsim_toplevel file, that was just to
help in the simulation!

5. On the next screen, select the FPGA you have. For the DE2, this is the Cyclone 2 EP2C35F672C6:

6. Click Finish. The project is now created. Have a look around! ;-)

7. When you are done, go to AssignmentsImport Assignments and select the Pin configuration
file:

Kuti Lusala Page 15


Circuits Electroniques-FPGA-Introduction au Verilog

8. Now, click on the synthesise button:

9. When everything has compiled, and your DE2 card is plugged-in, double click on program to
launch the programmer:

10. In the programmer, ensure the Hardware Setup correctly states USB_Blaster, and that the mode
is JTAG. Yep? Start!

11. Now observe the lights on your board, and bask in the wonder of electronics! Try playing around
with the verilog to slow down the LEDs, or try to make them go faster! What happens when it
goes too fast? ...?

Kuti Lusala Page 16


Circuits Electroniques-FPGA-Introduction au Verilog

Conclusion
Okay, this was a fairly long tutorial, but we covered the following items briefly:

 What verilog is and how to use it.


 How to simulate verilog in ModelSim.
 How to use Quartus to synthesize some verilog code and place it on your FPGA board.

We would like to stress how important verilog is for the rest of this course. Handling verilog “natively” is
essential, and an integral part of the rest of the course.

To help you revise, there is a small homework due for next week, please see the associated document.

Kuti Lusala Page 17


Circuits Electroniques-FPGA-Introduction au Verilog

Cas d’étude : Machine à états finis et Implémentation sur FPGA

Une machine à états finis est un circuit séquentiel dont la sortie dépend des entrées et/ou des différents
états décrivant son comportement.

La structure générale d’une machine à états finis est donnée ci-dessous :

Ainsi une machine à états finis est constituée d’une partie combinatoire qui est responsable du calcul du
prochain état en fonction de l’entrée et de l’état courant, d’une partie séquentielle qui stocke l’état
courant. La sortie du système dépend soit uniquement de l’état courant, on a alors une machine de
Moore, soit des entrées et de l’état courant, on a alors une machine Mealy.

Les machines à états finis sont généralement représentés par un diagramme appelé « diagramme
d’états ». Ce diagramme permet de visualiser l’évolution de la machine à états finis en fonction des
stimuli d’entrée et l’état courant. Les états sont représentés par des cercles, dans lesquels est inscrit le
nom attaché à l’état. Les transitions entre les états sont représentées par des arcs orientés reliant les
cercles. Les conditions permettant de déclencher les transitions sont notées sur les arcs. La valeur de
sortie est indiquée soit sur l’arc (séparée de l’entrée par le trait oblique /) ou à l’intérieur du celcle
(séparée du nom de l’état par un trait oblique:/).

A titre d’illustration, nous montrons sur la figure ci-dessous, une machine à états finis composé d’une
entrée, de trois états et d’une sortie.

Diagramme d’états

Kuti Lusala Page 18


Circuits Electroniques-FPGA-Introduction au Verilog

On sait donc voir qu’au signal de reset, le système est à l’état S1, et la sortie vaut 1. Tant que le signal
d’entrée sera à 0, la machine à états finis restera à l’état S1, et la sortie sera toujours à 1. Lorsque
l’entrée passe à 1, la machine à états évolue de l’état S1 à l’état S2, et la sortie devient 0. Pendant que le
système se trouve à l’état S2, si l’entrée passe à 0, le système retourne à l’état S1 et la sortie vaut 1, et si
l’entrée reste à 1, alors le système évolue de l’état S2 à l’état S3, et la sortie vaut 1. Dans l’état S3, si
l’entrée est à 1, le système va rester dans l’état S3 et la sortie demeure à 1, par contre si l’entrée passe à
0, le système passe de l’état S3 à l’état S1, et la sortie vaut 1, ainsi de suite.

Tableau d’états

La description faite ci-dessus, à l’aide du diagramme d’états, permet de comprendre le fonctionnement


du système, cependant pour implémenter la machine à états finis, il est plus intéressant de représenter
le diagramme d’états sous la forme d’un tableau appelé « tableau d’états ». Pour l’exemple ci-dessous le
tableau d’état est donné ci-dessous.

Etat courant Prochain Etat sortie

Entrée=0 Entrée=1

S1 S1 S2 1

S2 S1 S3 0

S3 S1 S3 1

Codage des états

Pour pouvoir continuer l’implémentation de la machine à états, les états doivent avoir une
représentation binaire. Ainsi pour trois états, une représentation à l’aide de 2 bits permettra de coder
tous les trois états. Ainsi les code binaire pour chaque état est donné ci-dessous :

S1 = « 00 » ; S2 = « 01 » ; S3 = « 10 ». Symboliquement l’état courant peut être représenté par les bits


« x2x1» et le prochain état par « y2y1». Le tableau d’états devient alors :

Kuti Lusala Page 19


Circuits Electroniques-FPGA-Introduction au Verilog

Etat courant Prochain Etat sortie

w=0 w=1

x2x1 y2y1 y2y1 z


S1 00 00 01 1

S2 01 00 10 0

S3 10 00 10 1

Partant du tableau d’états codés, on peut alors calculer, à l’aide du tableau de Karnaugh, les expressions
logiques du prochain état en fonction de l’état courant et de l’entrée. De la même manière on calcule la
sortie, soit en fonction d l’état courant uniquement ou en fonction de l’état courant et de l’entrée.

Calcul de y1

𝒚𝟏 = 𝒘𝒙𝟐 𝒙𝟏

Calcul de y2

𝒚𝟐 = 𝒘(𝒙𝟏 + 𝒙𝟐 )

Kuti Lusala Page 20


Circuits Electroniques-FPGA-Introduction au Verilog

Calcul de z

𝒛 = 𝒙𝟐 + 𝒙𝟏

Code verilog

Kuti Lusala Page 21


Circuits Electroniques-FPGA-Introduction au Verilog

Kuti Lusala Page 22

Vous aimerez peut-être aussi