Course Guide: Digital Design with Verilog HDL 🎓
This document describes the full content of the teaching module: 42 supervised hours (+ 8 h of personal project work), intended for 2nd/3rd-year engineering-school or bachelor's students (electrical engineering, industrial computing, telecommunications, embedded systems).
All the tools used are 100% free and open-source: Icarus Verilog (simulation), Yosys (synthesis), GTKWave (waveforms, optional).
📂 Repository Structure
The pack is organised in a modular way to make navigation easy for teachers and students:
| Folder | Content |
|---|---|
00_plan/ |
Module sheet, schedule of the 14 sessions, assessment rules, bibliography |
01_cours/ |
8 course chapters (C1 to C8) |
02_td/ |
5 tutorial (TD) sheets (TDn.md) and their solutions (corriges_TD.md) |
03_tp/ |
9 lab sessions (TP0 to TP8): enonce.md, src/ (student skeleton), tb/ (self-checking testbench), corrige/ (solution) |
04_examens/ |
DS (mid-term test), Final exam, Resit: papers, Verilog files, testbenches, solutions and marking schemes |
scripts/ |
Bash scripts: run.sh, synth.sh, check_env.sh, test_all.sh |
Makefile |
Shortcuts (make help) |
figures/ |
48 figures (PNG + SVG): real timing diagrams, Yosys schematics, state diagrams, measurement charts; galerie.html to browse them; make_all.sh to regenerate everything |
pdf/ |
PDF versions: course handout, tutorials, labs, exam papers, solutions (teacher) |
🚀 Quick Start (Ubuntu / Debian / WSL)
sudo apt update && sudo apt install -y iverilog yosys gtkwave
cd pack_verilog
scripts/check_env.sh # checks the installation
scripts/run.sh 03_tp/TP1_combinatoire src # tests YOUR code (src/ folder)
scripts/run.sh 03_tp/TP1_combinatoire corrige # tests the solution
make help
Each testbench prints a last line RESULT: PASS or RESULT: FAIL (n errors).
The script's exit code is 0 only on PASS: it can be used for automatic grading.
📊 Built-in Visual Tools
scripts/wave.sh <file.vcd> tb.clk tb.q:dec --grid 10 # PNG/SVG timing diagram (no GTKWave needed)
scripts/show.sh <module> <file.v> [--gates] # schematic of the circuit generated by Yosys (RTL or gates)
figures/make_all.sh # regenerates all the figures of the pack (graphviz + matplotlib)
Note: The figures are not drawn by hand. The timing diagrams come from real simulations, the schematics from
yosys show, the measurement charts from Yosys (cells per module/type, cost of adders and of the ALU) and from a GCD latency model validated on 400 RTL simulations.
👨🏫 Teacher's Guide
- Automatic validation:
make test(orscripts/test_all.sh) checks that all the solutions pass, that all the student skeletons fail (non-trivial testbench) and that the FIFO mutant is detected. - Validation result for this pack: "ALL CONSISTENT" (Icarus Verilog 12, Yosys 0.52+).
- Exam security: Do not distribute the
corrige/andmutant/folders, norcorriges_TD.md,corrige.mdandpdf/*enseignant*(teacher PDFs), before the end of the relevant sessions. - Assessment: The 3 exams are independent and of comparable difficulty; the resit uses different modules from the final exam.
- GCD case study: The GCD of TP8 reuses the architecture (control/datapath, req/resp interface, 8 ports, 54 bits) of the supplied Yosys report; chapter C8 and TD4 use the figures from that report.
🌐 Ecosystem & Support
This educational pack is developed and optimised by Zaxam.tech. If you are looking for tools to automate your chip-design flows (LibreLane, OpenROAD), discover HiveZe, our open-source EDA assistant.
- 🌍 Website: zaxam.net
- 📧 Contact: contact@zaxam.net
- ☕ Support the project: Buy me a coffee
- ⭐ GitHub Sponsors: Sponsor Zaxam.tech / Don-zak
Digital Design and Hardware Description in Verilog HDL
Module Sheet and Teaching Schedule
1. Module Sheet
| Title | Digital Design and Hardware Description in Verilog HDL |
| Audience | Engineering-school / applied bachelor's, 2nd–3rd year (electrical eng., computer eng., telecoms, embedded systems) |
| Contact hours | 42 h supervised (19.5 h lectures · 7 h tutorials (TD) · 14 h labs (TP) · 1.5 h mid-term test (DS)) + 8 h of independent project work |
| Credits / coefficient | 3 ECTS (to be adapted) |
| Prerequisites | Boolean algebra, combinational and sequential logic (flip-flops, counters), basic algorithmics, elementary use of the Linux terminal |
| Tools | Icarus Verilog, Yosys, GTKWave (optional), bash, make |
| Language of instruction | French in the original (English technical vocabulary kept: testbench, netlist, handshake…) |
Learning objectives
By the end of the module, the student is able to:
- Describe in Verilog (synthesisable subset) combinational circuits, sequential circuits and state machines;
- Structure a project hierarchically and in a parameterisable way (modules,
parameter,generate); - Verify a module with a self-checking testbench, using a reference model and random stimuli;
- Synthesise with Yosys, read a report (
stat), and detect classic errors (latches, bus widths); - Design a processing unit with a control / datapath split (GCD case study);
- Automate testing and synthesis with bash scripts and a
Makefile.
2. Schedule of the 14 Sessions (3 h each)
Each session has a lecture block and an application block; the final exam (2 h) takes place in week 15.
| Session | Lecture (1 h 30) | Application (1 h 30) | Deliverable / assessment |
|---|---|---|---|
| 1 | C1 Design flow, HDL, Verilog, simulation | TP0 Getting started: bash, iverilog, GTKWave | |
| 2 | C2a Types, vectors, operators, assign |
TD1 Combinational logic | |
| 3 | C2b always @*, if, case, latches |
TP1 Mux, adder (hierarchy) | Auto-test TP1 |
| 4 | C2c Arithmetic, widths, signed/unsigned | TP2 8-bit ALU, 7-segment decoder | Auto-test TP2 |
| 5 | C3a Flip-flops, registers, reset, clock | TD2 Sequential logic | |
| 6 | C3b Counters, blocking vs non-blocking | TP3 Counter, LFSR, edge detector | Auto-test TP3 |
| 7 | C4a FSM: Moore, Mealy, state encoding | TD3 State machines | |
| 8 | C4b FSM: 3-block style, good practice | TP4 Sequence detector, vending machine | Auto-test TP4 |
| 9 | DS (1 h 30) | C5 Hierarchy, parameters, generate, memories (1 h 30) |
DS graded |
| 10 | C6a Testbench: clock, stimuli, $display |
TP5 N-bit adder, popcount, register file | Auto-test TP5 |
| 11 | C6b Self-checking, scoreboard, mutation | TP6 FIFO + scoreboard testbench + mutant | Auto-test TP6 |
| 12 | C7 Yosys synthesis, reading the report | TP7 Synthesis, latches, adder comparison | TP7 report |
| 13 | C8 Case study: GCD (control/data) | TD4 Reading a real Yosys report | |
| 14 | TP8 GCD project (2 h) | TD5 Revision / typical exam questions (1 h) | Project handed in (+ 8 h independent) |
| 15 | Final exam (2 h, on computer) | Exam graded | |
| — | Resit (1 h 30, later session) | Replaces the exam mark |
Totals: lectures 19.5 h · TD 7 h (TD1 to TD4: 1 h 30 each, TD5: 1 h) · TP 14 h (TP0–TP7: 1 h 30 each, TP8: 2 h) · DS 1 h 30 = 42 h.
3. Assessment
| Component | Weight | Rules |
|---|---|---|
| Lab work (TP) | 20 % | Automatic tests RESULT: PASS (TP1–TP6) + TP7 report |
| GCD project (TP8) | 20 % | Controller + synthesis report + completed testbench; 5-minute defence |
| DS (session 9) | 20 % | 1 h 30, on computer, automatic grading + code review |
| Final exam | 40 % | 2 h, on computer: part A written (8 pts) + part B Verilog (12 pts) |
| Resit | Replaces the final exam mark; continuous assessment is kept |
Automatic grading: a script (scripts/run.sh) produces PASS/FAIL and the list of errors. The mark
remains at the teacher's discretion: a code review (readability, absence of latches, synchronous style) is recommended.
4. Equipment and Organisation
- Computer room with Linux (or WSL2 under Windows); installation:
sudo apt install iverilog yosys gtkwave. - One folder per student, a copy of
pack_verilog/without thecorrige/folders. - Git repository recommended for the project (one commit per feature).
5. Bibliography
- S. Palnitkar, Verilog HDL: A Guide to Digital Design and Synthesis, Prentice Hall.
- IEEE Std 1364-2005, Verilog Hardware Description Language.
- D. Harris, S. Harris, Digital Design and Computer Architecture, Morgan Kaufmann.
- C. Cummings, Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill! (SNUG 2000).
- Yosys documentation: https://yosyshq.readthedocs.io; Icarus Verilog: https://steveicarus.github.io/iverilog/.
Chapter 1 — Introduction: from Specification to Circuit
Duration: 1 h 30 · Session 1 · Associated lab: TP0
1.1 Objectives
Place the Verilog language within the digital design flow, and install and use the free tool chain.
1.2 Why a Hardware Description Language (HDL)?
A modern integrated circuit contains from a few thousand to several billion gates: drawing the schematic by hand is no longer possible. An HDL lets you describe behaviour or structure, simulate it before fabrication, and then automatically synthesise it into logic gates (ASIC) or configurable blocks (FPGA).
An HDL is not a programming language: a Verilog description describes hardware that works in parallel. Every
assignand everyalwaysblock is a piece of circuit that is always "active".
1.3 The Design Flow
This module covers the first three steps (RTL, simulation, logic synthesis). Place-and-route and timing analysis are presented only as an outlook.
1.4 Levels of Abstraction
| Level | Example | Use |
|---|---|---|
| Behavioural | always @* y = a + b; |
Modelling, testbench |
| RTL (Register Transfer Level) | registers + logic between registers | Synthesis level |
| Structural | instances of modules / gates | Hierarchy, netlists |
1.5 Verilog: First Notions
A module is the basic building block: it has ports (input, output) and a body.
module half_adder (
input a, b,
output s, c
);
assign s = a ^ b; // sum
assign c = a & b; // carry
endmodule
- Verilog is case-sensitive; comments:
//and/* ... */. assignstatements andalways/initialblocks execute in parallel.- Only a subset of the language is synthesisable; the rest (
initialwith delays,$display,#10…) is used for simulation and testbenches.
1.6 The Module's Tool Chain
| Tool | Role | Typical command |
|---|---|---|
iverilog |
compiles the sources for simulation | iverilog -g2005 -o sim.vvp tb.v dut.v |
vvp |
runs the simulation | vvp sim.vvp |
gtkwave |
displays *.vcd files |
gtkwave tp0.vcd |
yosys |
logic synthesis | yosys -p "read_verilog dut.v; synth -top dut; stat" |
1.7 Essential bash Reminders
pwd; ls -l; cd folder; mkdir -p a/b; cp src dst; mv a b; rm file
cat file; less file; head -n 20 file; grep -n "pattern" file
command1 | command2 # pipe: output of 1 = input of 2
command > log.txt # redirection; >> to append
./script.sh && echo OK # conditional chaining
echo $? # exit code of the last command (0 = success)
1.7bis The Pack's Visual Tools
Three commands let you see what you are designing, without installing a heavy graphical interface:
scripts/wave.sh <file.vcd> tb.clk tb.q:dec # PNG/SVG timing diagram from a VCD
scripts/show.sh adder4 src/tp1_comb.v # circuit schematic (RTL level) generated by Yosys
scripts/show.sh ZeroComparator src/x.v --gates # schematic after synthesis (gates)
The figures/ folder contains all the figures of the course (figures/galerie.html to browse them). They are produced
by real simulations and syntheses: figures/make_all.sh regenerates them.
1.8 Key Points to Remember
- Verilog describes hardware; everything executes in parallel.
- The flow: RTL → simulation → synthesis → implementation.
- Always validate by simulation before synthesising.
- Every lab is tested with
scripts/run.sh <folder> src: aRESULT: PASSline concludes the simulation.
Chapter 2 — Combinational Logic in Verilog
Duration: 4 h 30 (3 lecture sessions, S2 to S4) · TD1, TP1, TP2
2.1 Data Types
wire: a wire, driven byassignor by a module output;reg: a variable assigned in a procedural block (always,initial).regdoes not mean "register": depending on the block, aregvariable becomes either a wire (combinational logic) or a flip-flop (clocked block).- Vectors:
wire [7:0] bus;(bit 7 = most significant). Memories:reg [7:0] mem [0:15];. - 4-state values:
0,1,x(unknown),z(high impedance).
2.2 Literals
<size>'<base><value>: 4'b1010, 8'hFF, 12'd100, 16'sd-5 (signed). Without a size: 32 bits (a source of errors!).
2.3 Operators
| Family | Operators | Remark |
|---|---|---|
| Bitwise | ~ & \| ^ ~^ |
result has the same width as the operands |
| Logical | ! && \|\| |
1-bit result (true/false) |
| Reduction | &x \|x ^x ~&x |
single operand → 1 bit (e.g. ^x = parity) |
| Arithmetic | + - * / % |
/ and % are costly or not synthesisable |
| Shift | << >> >>> |
>>> is arithmetic if the operand is signed |
| Comparison | == != < <= > >= === !== |
===/!== also compare x/z (testbench) |
| Concatenation | {a, b}; replication {4{a}} |
{8{1'b0}} = 8'h00 |
| Conditional | s ? a : b |
multiplexer |
2.3bis Widths: the Rule that Catches Everybody
In Verilog, the width of an expression is that of the largest of its operands and of the assignment target.
wire [7:0] a, b; wire [8:0] s;
assign s = a + b; // OK: the addition is done on 9 bits, the carry is kept
wire [7:0] t = a + b; // carry lost (silent truncation)
assign s = {1'b0, a} + {1'b0, b}; // explicit, recommended
2.4 Dataflow Description: assign
module mux2 #(parameter W = 8) (input [W-1:0] a, b, input s, output [W-1:0] y);
assign y = s ? b : a;
endmodule
2.5 Behavioural Description: always @*
For if/case, we use a procedural block sensitive to all its inputs: always @*.
module dec2to4 (input [1:0] a, input en, output reg [3:0] y);
always @* begin
y = 4'b0000; // default value
if (en) case (a)
2'd0: y = 4'b0001;
2'd1: y = 4'b0010;
2'd2: y = 4'b0100;
2'd3: y = 4'b1000;
endcase
end
endmodule
Rules: blocking assignments (=) in a combinational block; every output is assigned a value
in all cases (default value at the top of the block, or a final default: / else).
2.6 The Trap of the Inferred Latch
If a variable is not assigned on every path of an always @* block, the synthesiser must
remember the old value: it creates an unwanted latch.
always @* if (en) y = a; // BAD: latch (y is held when en = 0)
always @* begin y = 1'b0; if (en) y = a; end // GOOD
Yosys reports the latch ($_DLATCH_), and scripts/synth.sh then prints a warning (TP7).
2.7 case, casez, Priority
if / else if creates a priority (chain), case a parallel multiplexing. casez accepts ? as a
wildcard (casez (r) 4'b1???: ...). Always finish with default.
2.8 Functions
function [3:0] popcnt8 (input [7:0] x);
integer i;
begin popcnt8 = 0; for (i = 0; i < 8; i = i + 1) popcnt8 = popcnt8 + x[i]; end
endfunction
A function is combinational, with no delay; a for loop is unrolled at synthesis.
2.9 Signed Arithmetic
Declare signed for two's-complement numbers: wire signed [7:0] a;. Mixing signed and unsigned
in the same expression ⇒ everything is interpreted as unsigned. To sign-extend: {{4{a[3]}}, a}.
2.10 Key Points
- A combinational block =
always @*+=+ all outputs assigned in all cases. - Beware of widths and unsized literals.
xin simulation = uninitialised signal or conflict: to be tracked down.- An inferred latch is almost always a description error.
Chapter 3 — Synchronous Sequential Logic
Duration: 3 h (S5–S6) · TD2, TP3
3.1 The Synchronous Principle
The entire state of the circuit is stored in D flip-flops driven by one common clock. Between two edges, the combinational logic computes the next state; at the edge, it is stored. Physical constraints: setup time (data stable before the edge) and hold time (stable after), verified by static timing analysis (STA), not by functional simulation.
3.2 The Clocked Block
always @(posedge clk) begin
q <= d; // NON-blocking assignment
end
An always @(posedge clk) block describes flip-flops: every reg assigned inside it becomes a register.
3.3 Reset
Synchronous (convention of this course: active high, evaluated at the clock edge):
always @(posedge clk) if (rst) q <= 8'd0; else q <= d;
Asynchronous (acts immediately, independently of the clock):
always @(posedge clk or posedge rst) if (rst) q <= 8'd0; else q <= d;
Synchronous reset is better suited to FPGAs and timing analysis; asynchronous reset is common in ASICs (in which case provide a synchronised release). Never mix the two styles in one project without a reason.
3.4 Register with Enable
always @(posedge clk) if (en) q <= d; // synthesised: flip-flop with enable ($_DFFE_PP_ in Yosys)
Never "gate" the clock by hand (clk & en): use an enable.
3.5 Blocking vs Non-blocking Assignments — THE Golden Rule
| Clocked block (sequential) | always @* block (combinational) |
|
|---|---|---|
| Operator | <= (non-blocking) |
= (blocking) |
A revealing example (3-stage shift register):
always @(posedge clk) begin q1 <= d; q2 <= q1; q3 <= q2; end // GOOD: 3 flip-flops in series
always @(posedge clk) begin q1 = d; q2 = q1; q3 = q2; end // BAD: q3 = d, only one effective flip-flop
With <=, all the right-hand-side values are read before the edge, then all the updates are
applied "at the same time": this is the behaviour of a real register.
Other rules: a reg is assigned in only one always block; do not mix = and <= in the same block.
3.6 Classic Counters and Registers
module counter #(parameter W = 4) (input clk, rst, en, output reg [W-1:0] q);
always @(posedge clk) begin
if (rst) q <= {W{1'b0}};
else if (en) q <= q + 1'b1; // natural overflow: modulo 2^W
end
endmodule
Shift register: sh <= {sh[W-2:0], din};; LFSR: shift + XOR of feedback bits (TP3).
3.7 Two-block Style: Register + Next-state Logic
reg [3:0] state, next;
always @(posedge clk) if (rst) state <= 4'd0; else state <= next; // sequential
always @* next = state + 1'b1; // combinational
This split structures the code and will be generalised to FSMs (chapter 4).
3.8 Asynchronous Signals and Metastability
An unsynchronised external signal (button, another clock domain) can violate setup/hold and make the flip-flop metastable. The basic remedy: a two-flip-flop synchroniser.
reg s1, s2;
always @(posedge clk) begin s1 <= async_in; s2 <= s1; end // use s2
3.9 Key Points
- Sequential:
always @(posedge clk)+<=. - A single, clearly documented reset style.
if (en)= enable, no manual clock gating.- Every incoming asynchronous signal is resynchronised.
Chapter 4 — Finite State Machines (FSM)
Duration: 3 h (S7–S8) · TD3, TP4
4.1 Models
An FSM is defined by a set of states, a next-state function and an output function.
- Moore: output = f(state). Stable, synchronous output, delayed by one cycle.
- Mealy: output = f(state, inputs). Immediate reaction, but depends on the inputs (risk of glitches, combinational input→output paths).
4.2 Recommended Style: Three Blocks
module seq_moore (input clk, rst, in, output out); // "1011" detector with overlap
localparam S0 = 3'd0, S1 = 3'd1, S10 = 3'd2, S101 = 3'd3, S1011 = 3'd4;
reg [2:0] state, next;
always @(posedge clk) // (1) state register
if (rst) state <= S0; else state <= next;
always @* begin // (2) next state
next = state; // default value: stay
case (state)
S0: next = in ? S1 : S0;
S1: next = in ? S1 : S10;
S10: next = in ? S101 : S0;
S101: next = in ? S1011 : S10;
S1011: next = in ? S1 : S10;
default: next = S0; // unused states -> safe return
endcase
end
assign out = (state == S1011); // (3) output (Moore)
endmodule
For the Mealy version, the output becomes assign out = (state == S101) & in; and the S1011 state disappears.
4.3 Design Method
- List the states, naming what each one remembers.
- Draw the diagram (states, transitions labelled with the inputs, outputs).
- Check completeness (all inputs handled in every state) and mutual exclusivity of the transitions.
- Code it in three blocks, with
defaultand a default value fornext. - Test with a reference model and random sequences.
4.4 State Encoding
| Encoding | Bits for N states | Advantage | Use |
|---|---|---|---|
| Binary | ⌈log₂ N⌉ | few flip-flops | small FSMs |
| One-hot | N | simple, fast next-state logic | FPGA, large FSMs |
| Gray | ⌈log₂ N⌉ | only 1 bit changes per transition | counters, clock-domain crossing |
Yosys can automatically re-encode an FSM (fsm in synth), provided it detects it.
4.5 Good Practice
- Always provide a reset to a defined initial state.
- All outputs assigned in all states (default values): no latch.
- Name the states with
localparam; avoid magic numbers. - If a Mealy output feeds a register in another module, think about the chain of combinational paths.
- val/rdy interfaces (handshake): a transfer takes place when
val && rdyat the clock edge (see GCD, chapter 8).
4.6 Key Points
- Moore vs Mealy: one-cycle latency versus dependence on the inputs.
- Three blocks: register, next state, outputs.
defaultand default values everywhere.
Chapter 5 — Hierarchy, Parameters and Generation
Duration: 1 h 30 (S9) · TP5
5.1 Module Instantiation
adder4 u_add (.a(x), .b(y), .cin(1'b0), .s(sum), .cout(co)); // connection BY NAME (recommended)
Positional connection (adder4 u (x, y, 1'b0, sum, co)) is fragile: a changed port order silently breaks the circuit.
An unconnected port must be left open explicitly: .cout(). The instance name (u_add) is mandatory.
5.2 Parameters
module counter #(parameter W = 8, parameter MAXV = 255) (...);
counter #(.W(12), .MAXV(4000)) u_c (...); // override at instantiation
parameter: can be modified from outside;localparam: internal constant (e.g.localparam AW = $clog2(DEPTH);).$clog2(n): ⌈log₂ n⌉, useful for sizing counters and addresses.
5.3 generate
Repetition or conditional instantiation at elaboration (before simulation/synthesis).
genvar i;
generate
for (i = 0; i < N; i = i + 1) begin : g_bit // the block name is mandatory
fa1 u_fa (.a(a[i]), .b(b[i]), .cin(c[i]), .s(s[i]), .cout(c[i+1]));
end
endgenerate
generate if (FAST) ... else ... selects an architecture according to a parameter.
5.4 Memories
reg [7:0] mem [0:255]; // 256 words of 8 bits
always @(posedge clk) if (we) mem[waddr] <= wdata; // synchronous write
assign rdata = mem[raddr]; // asynchronous read (or registered for an FPGA RAM)
initial $readmemh("init.hex", mem); // initialisation (simulation / FPGA)
A large memory is mapped onto the FPGA's dedicated RAM; in an ASIC a memory compiler (macro) is used.
5.5 Organising a Project
- One module per file, file name = module name;
- a top-level module (top) that only connects;
- separate the datapath (registers, operators) from the control (FSM) — see chapter 8;
src/,tb/,scripts/folders; aMakefileto automate everything.
5.6 Key Points
- Instantiate by name, override parameters by name.
generate= repetition of hardware, not an execution loop.- A clear hierarchy = code that can be tested module by module.
Chapter 6 — Verification: Writing a Good Testbench
Duration: 3 h (S10–S11) · TP5, TP6
6.1 Structure of a Testbench
A testbench is a module with no ports that instantiates the DUT (Device Under Test), generates the stimuli and checks the outputs.
`timescale 1ns/1ps
module tb;
reg clk = 0, rst = 1; reg [7:0] d; wire [7:0] q;
always #5 clk = ~clk; // clock with a 10 ns period
my_reg dut (.clk(clk), .rst(rst), .d(d), .q(q));
initial begin
$dumpfile("tb.vcd"); $dumpvars(0, tb); // waveforms for GTKWave
repeat (3) @(negedge clk); rst = 0;
...
$finish;
end
endmodule
6.2 Stimulus Generation and Synchronisation
- Delay:
#10;; waiting for an event:@(posedge clk),@(negedge clk),wait (cond). - Good race-avoidance practice: apply the inputs on the falling edge (
@(negedge clk)) and sample on the rising edge: the DUT sees stable inputs at the active edge. - Random:
$random(32-bit signed);{$random} % Nfor a positive integer; seed:$random(seed). - Files:
$readmemh("vectors.hex", tab). task: a subroutine in which delays are allowed (sending a frame, a transaction…).
6.3 Self-checking
Inspecting waveforms by eye does not scale and cannot be automated. A good testbench:
- computes the expected result with a reference model (a behavioural function, independent of the DUT);
- compares with
!==(which also detectsx/z, unlike!=); - counts the errors and ends with a machine-readable verdict:
if (errors == 0) $display("RESULT: PASS"); else $display("RESULT: FAIL (%0d errors)", errors);
$finish;
The pack's testbenches follow this convention: scripts/run.sh returns code 0 only on PASS.
6.4 Scoreboard and Random Verification
The scoreboard is a reference model updated in parallel with the DUT and compared on every cycle (TP6: reference FIFO as a circular array). Combine: * directed tests: corner cases (full, empty, 0, maximum value, overflow); * random tests: a large number of cycles, several profiles (frequent writes, frequent reads, bursts).
6.5 Verification Quality: Mutation Testing
How do you know whether a testbench is any good? You deliberately inject a bug (a mutant) into the DUT;
a good testbench must fail. TP6 provides mutant/fifo_sync.v (a FIFO declared full one word too early):
scripts/run.sh 03_tp/TP6_testbench_fifo mutant must print FAIL.
6.6 Coverage (outlook)
Line, branch, FSM-state and functional coverage. Verilator and commercial simulators provide coverage tools; the idea: measure what the tests have actually exercised.
6.7 Classic Testbench Mistakes
- Forgetting
$finish→ endless simulation (the clock never stops); provide a watchdog (timeout). - Comparing with
!=instead of!==: anxgoes unnoticed. - Driving the DUT on the active edge: race condition.
- A reference model copied from the DUT: it reproduces the same errors; write it independently (another algorithm, from the spec).
6.8 Key Points
- Testbench = DUT + stimuli + reference model + automatic verdict.
- Inputs on
negedge, observation after the edge. - Evaluate the testbench by mutation.
Chapter 7 — Logic Synthesis with Yosys
Duration: 1 h 30 (S12) · TP7, TD4
7.1 What Is Synthesis?
Transforming an RTL description into an equivalent network of gates (netlist), optimised for a target
(FPGA or ASIC cell library). Yosys is an open-source synthesiser; its synth script chains
together elementary passes.
7.2 The Main Passes of synth -top <module>
| Pass | Role |
|---|---|
hierarchy |
builds the hierarchy from the top module, removes unused modules |
proc |
converts always/if/case blocks into multiplexers and flip-flops; detects latches (proc_dlatch) |
opt / opt_expr |
logic simplifications, constant propagation, removal of dead logic |
fsm |
detects and re-encodes state machines |
memory |
infers memories |
techmap |
replaces operators (+, <, …) with elementary gates |
abc |
optimises and maps the logic onto a set of generic gates |
stat |
prints the statistics (cells, wires, hierarchy) |
Command used in this module:
yosys -p "read_verilog gcd.v; synth -top gcd; stat"
# or, with our script: scripts/synth.sh gcd file1.v file2.v
7.3 Reading a stat Report
Each Number of cells line is followed by the breakdown by cell type. Yosys's generic logic cells:
| Cell | Meaning |
|---|---|
$_AND_, $_OR_, $_XOR_, $_XNOR_, $_NOT_, $_NAND_, $_NOR_ |
2-input gates (1 input for NOT) |
$_ANDNOT_, $_ORNOT_ |
A & ~B, A \| ~B (gates with one inverted input) |
$_MUX_ |
2-to-1 multiplexer |
$_DFF_P_ |
D flip-flop, rising edge |
$_DFFE_PP_ |
D flip-flop with enable (first P = clock on rising edge, second P = active-high enable) |
$_SDFF_PP0_ |
flip-flop with synchronous reset (clk P, active-high reset, reset value 0) |
$_DLATCH_P_ |
latch: almost always a bug |
With -top, the report is presented per module, followed by a design hierarchy section giving the cumulative total
over the whole hierarchy (number of instances × content).
Warning:
statwithout a library counts generic cells, not mm² or nanoseconds. For real area, you supply a.liblibrary (stat -liberty cells.lib); for critical-path time, you use an STA tool (for example OpenSTA). The number of cells is a useful relative indicator for comparing two architectures.
7.4 Example: "16 bits equal to zero"
The case-study report (chapter 8) gives for a 16-bit ZeroComparator: 15 cells
(3 $_ANDNOT_, 1 $_NOR_, 11 $_OR_). It is a reduction tree: a 16-bit OR requires 15 2-input
gates (n − 1). When interpreting a result, always relate it to the expected structure.
7.5 Errors Detected at Synthesis
- Inferred latch (incomplete
if/case) →$_DLATCH_instat;Latch inferredmessage in the log. - Inconsistent bus width (
Resizingwarnings,Warning: ... width). - Signal never driven (
undriven), combinational loop. initialwith a value: accepted for FPGAs only; avoid in generic RTL.
7.6 Post-synthesis Simulation
yosys -p "read_verilog gcd.v; synth -top gcd; write_verilog -noattr gcd_syn.v"
iverilog -g2005 -o gl.vvp tb_gcd.v gcd_syn.v && vvp gl.vvp # same testbench, gate-level netlist
The same testbench must pass on the netlist: this is an equivalence check by simulation (formal proof, which is more rigorous, is outside the syllabus).
7.7 Key Points
proc→opt→fsm/memory→techmap→abc→stat.- Reading a report: flip-flop types, number of cells per module, hierarchy.
- Zero latches in clean synchronous code.
Chapter 8 — Case Study: the GCD Computation Unit
Duration: 1 h 30 (S13) · TD4, TP8 (project)
8.1 Specification
Compute the greatest common divisor of two 16-bit integers A and B using Euclid's algorithm (subtractions and swaps), with a handshake interface:
- request:
req_val,req_rdy,req_msg[31:0] = {A[15:0], B[15:0]}; - response:
resp_val,resp_rdy,resp_msg[15:0]; clk,reset: in total 8 ports, 54 bits (1+1+32+1+1+16+1+1).
A transfer takes place at a clock edge where val and rdy are both 1.
8.2 Algorithm
while B ≠ 0:
if A < B: swap A and B
else : A ← A − B
result: A
Corner cases: gcd(a, 0) = a; gcd(0, b) = b (one swap is enough); gcd(0, 0) = 0.
8.3 Control / Datapath Architecture
- Datapath: 2 16-bit registers with enable (A, B), a 3-way multiplexer (input / A−B / B)
for A, a 2-way multiplexer (input / A) for B, a subtractor, an
A<Bcomparator, aB=0detector. - Controller: 3-state FSM (2-bit state register with synchronous reset).
| State | Outputs | Transition |
|---|---|---|
| IDLE | req_rdy=1, loads A and B from req_msg |
req_val → CALC |
| CALC | if B≠0: swap (if A<B) otherwise A←A−B |
B=0 → DONE |
| DONE | resp_val=1, resp_msg = A |
resp_rdy → IDLE |
8.4 Verification
tb_gcd.v: Euclid reference function (modulo), corner cases ((0,0), (a,0), (0,b), (65535,1)…),
150 random cases and random back-pressure on resp_rdy; check that resp_val is held as long as
resp_rdy is low.
8.5 Analysis of the Yosys Report (run of synth -top gcd; stat)
The study's reference report concerns an automatically generated version of the GCD (same architecture). Figures taken from it:
| Module | Cells | Remark |
|---|---|---|
16-bit Subtractor |
98 | largest block (≈ 30 % of the total) |
16-bit LtComparator |
72 | magnitude comparator |
3-way Mux (16 bits) |
67 | $_MUX_ + logic |
2-way Mux (16 bits) |
16 | 16 $_MUX_ |
RegEn (×2) |
2 × 16 | 16 × $_DFFE_PP_ each |
ZeroComparator |
15 | tree of 15 gates (n − 1) |
RegRst (state) |
2 | 2 × $_SDFF_PP0_ |
| Controller (logic only) | 26 | |
| Total (hierarchy) | 328 | of which 34 flip-flops (32 $_DFFE_PP_ + 2 $_SDFF_PP0_) |
Check: 98 + 72 + 67 + 16 + 32 + 15 + (26 + 2) = 328 cells. The number of flip-flops (34) matches the architecture: 16 (A) + 16 (B) + 2 (state).
The pack's GCD, rewritten by hand with the same hierarchy, gives about 341 cells after synth -top gcd:
the difference of a few percent is normal (different description style, ABC optimisation); the architecture and
the number of flip-flops (34) are identical. More important than the total: identify which block dominates and
why.
8.6 Optimisation Ideas (project, bonus)
- Remove the comparator by reusing the sign bit of the subtraction (
A − Bon 17 bits). - Replace the swap with a computation of
|A − B|(Stein's binary algorithm): shifts instead of repeated subtractions. - Compare the
statreports before/after; check thattb_gcdstill passes.
Latency: a computation whose duration depends on the data
Each subtraction or swap costs one cycle. For two random 16-bit numbers the typical latency is about 50 cycles, but
the worst case gcd(65535, 1) requires 65,535 operations. The chart below is based on 20,000 pairs with a model validated
on 400 RTL simulations (constant offset of 1 cycle for the handshake).
8.7 Key Points
- Separating control and data makes the code readable, testable and reusable.
- The val/rdy interface is a contract; the testbench must check it, not just the result.
- We validate by simulation, then synthesise, read the report and re-simulate the netlist.
FPGA Lab Work on the iCEBreaker Board 🎓
This self-contained lab module (27 hours) complements a digital design course in Verilog (it assumes the basics are already acquired: modules, always, state machines, testbench).
Required hardware: an iCEBreaker board (Lattice iCE40UP5K FPGA, 12 MHz clock, USB/FTDI) and its "LED & buttons" Pmod (5 LEDs + 3 buttons). Software (Linux / WSL2): Icarus Verilog, Yosys, nextpnr-ice40, IceStorm (icepack, iceprog).
sudo apt update && sudo apt install -y iverilog yosys nextpnr-ice40 fpga-icestorm gtkwave
🧪 The 7 Practical Labs
| Lab | Theme | FPGA concept highlighted |
|---|---|---|
| F0 | Getting started: blinker + chaser | Complete flow, constraints, no reset (register initialisation), resource report |
| F1 | Mechanical buttons | Asynchronous input, synchroniser, saturating-counter debounce filter |
| F2 | PWM and LED "breathing" | Inferred block memory (BRAM), file-initialised ROM, gamma correction |
| F3 | USB serial terminal | UART RX, mid-bit sampling, clock tolerance |
| F4 | Frequency, PLL and DSP | Timing closure, reading a critical path, 12→48 MHz PLL, DSP block |
| F5 | Memory-based sequencer | Dual-port RAM, read latency, control FSM |
| F6 | Project: reflex game | Integration, milliseconds, randomness, serial link, the division trap |
| F7 | Validation on the board | Measurements, report, presentation |
🚀 Usage (Commands)
scripts/fpga.sh sim F1_entrees_boutons src # simulation of YOUR code (RESULT: PASS?)
scripts/fpga.sh all F1_entrees_boutons src # simulation + synthesis + routing + bitstream + checks
scripts/fpga.sh prog F1_entrees_boutons src # programs the board in SRAM (lost at power-off)
scripts/fpga.sh flash F1_entrees_boutons src # programs the flash memory (persistent)
Each lab is validated in three steps: simulation (RESULT: PASS), synthesis flow (frequency and resources within spec), then verification on the board (checklist in each statement).
⚠️ Validation Status & Limits
Validated: The solutions of the 7 labs pass simulation + synthesis + place-and-route + bitstream generation. The student skeletons fail (scripts/selftest.sh: ALL CONSISTENT). Tools: Icarus Verilog 12, Yosys 0.33, nextpnr-ice40 0.6.
Important limit: This pack has not been run on a physical board (no board was available when it was produced). The pins in the file board/icebreaker.pcf are taken from the board's public documentation and must be checked by the teacher on a real board before the first session (see the board guide).
🌐 Ecosystem & Support
This FPGA module is part of the Open Source Educational Pack developed by Zaxam.tech.
- 🌍 Website: zaxam.net
- 🛠️ Our EDA tool: HiveZe (AI assistant).
- 📧 Academic contact: contact@zaxam.net
- 💖 Support the project:
- ☕ Buy me a coffee
- ⭐ GitHub Sponsors: Sponsor Zaxam.tech / Don-zak
Guide to the iCEBreaker Board and the Tool Chain
1. The Board
| Element | Pin (SG48) | Active level |
|---|---|---|
12 MHz clock (CLK) |
35 | — |
On-board red LED (LEDR_N) |
11 | lit when 0 |
On-board green LED (LEDG_N) |
37 | lit when 0 |
On-board button (BTN_N) |
10 | pressed = 0 |
Pmod: LED[0] … LED[4] |
26, 27, 25, 23, 21 | lit when 1 |
Pmod: BTN[0] … BTN[2] |
20, 19, 18 | pressed = 1 |
UART: RX (FPGA input) / TX (FPGA output) |
6 / 9 | idle = 1 |
Check this first. These pin numbers are those published for the board and its "LED & buttons" Pmod plugged into the PMOD2 connector, but the pack could not be tested on hardware. Compare
board/icebreaker.pcfwith the official file in the board's repository and with the silkscreen of your module before programming. A pin error usually produces only a circuit that "does nothing", but never connect an external source without checking the voltages (the FPGA's inputs/outputs are 3.3 V).
2. Tool Chain
| Step | Tool | Role | Result |
|---|---|---|---|
| Simulation | iverilog, vvp |
runs the testbench | RESULT: PASS / FAIL |
| Synthesis | yosys (synth_ice40) |
RTL → LUTs, flip-flops, BRAM, DSP | top.json, cell report |
| Place-and-route | nextpnr-ice40 |
places and wires; timing analysis | top.asc, Fmax, utilisation |
| Bitstream | icepack |
converts .asc |
top.bin |
| Programming | iceprog |
sends to the board | SRAM (-S) or flash |
scripts/fpga.sh chains these steps; the intermediate files are in build_src/ or build_corrige/ of each lab.
The script only constrains the pins that are actually used by the top-level module.
3. Programming
fpga.sh prog: volatile configuration (SRAM): fast, ideal in lab sessions; the board forgets everything at power-off.fpga.sh flash: writes the flash memory: the circuit restarts by itself.- USB permissions (Linux): if
iceproganswers "Can't find iCE FTDI USB device", create the following udev rule, then unplug and replug:
echo 'ACTION=="add", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6010", MODE:="666"' | sudo tee /etc/udev/rules.d/53-lattice-ftdi.rules
sudo udevadm control --reload-rules && sudo udevadm trigger
- WSL2: the USB port is not visible by default: use
usbipd(on the Windows side) to attach the board. - The FTDI chip exposes two channels: one is used for programming, the other for the serial port (often
/dev/ttyUSB1). Terminal:screen /dev/ttyUSB1 115200(quit: Ctrl-A then K); orscripts/serial_check.py /dev/ttyUSB1for lab F3.
4. FPGA Particularities for the Student Coming from Simulation
- No reset on the board: registers receive their value at configuration: initialise them at their declaration
(
reg [7:0] r = 0;). This is accepted by Yosys for the iCE40; it is not portable to all devices. - An FPGA is not a processor: an "always active" module consumes resources permanently.
- Time is counted in cycles: 12 MHz → 83.3 ns per cycle; 1 s = 12,000,000 cycles (24-bit counter).
- Simulation is not enough: a correct description can be too slow (Fmax) or too big; only place-and-route tells you.
- Specialised resources (BRAM, DSP, PLL) are obtained through a specific coding style or by instantiation.
5. Troubleshooting
| Symptom | Probable cause | Action |
|---|---|---|
iceprog: device not found |
udev rule, charge-only cable, WSL | see §3 |
Nothing happens after prog |
.pcf pins, active levels, wrong clock |
re-read §1; light the green LED with LEDG_N = 0 |
| Inverted LED | active level misunderstood | on-board LEDs active at 0; Pmod LEDs active at 1 |
| "Jumpy" buttons | no filtering | F1 |
| Unreadable serial characters | wrong baud rate or FTDI channel | 115200 8N1; channel B |
nextpnr: FAIL at X MHz |
combinational path too long | F4: pipeline, DSP |
Progression, Assessment and Validation on the Board
1. Proposed Schedule (27 h)
| Session | Duration | Lab | Objective | Deliverable |
|---|---|---|---|---|
| 1 | 3 h | F0 | Complete tool chain, first configuration of the board | RESULT: PASS + video/photo of the board |
| 2 | 3 h | F1 | Reliable mechanical inputs | Test + board validation |
| 3 | 3 h | F2 | PWM, BRAM, ROM | Test + board validation |
| 4 | 3 h | F3 | Serial terminal | Test + serial_check.py |
| 5 | 3 h | F4 | Frequency, PLL, DSP | Table of the three Fmax values |
| 6 | 3 h | F5 | RAM and sequencer | Test + board validation |
| 7–8 | 6 h | F6 | Reflex game project | Test + demonstration |
| 9 | 3 h | F7 | Measurements, report, presentation | Report + oral |
2. Indicative Marking Scheme (/20)
| Criterion | Points | Measurement |
|---|---|---|
Simulation: testbench PASS on labs F0–F6 |
6 | automatic (fpga.sh sim) |
Flow: synthesis, routing and Fmax within spec (fpga.sh all) |
4 | automatic |
| Demonstration on the board (checklist of each lab) | 5 | observation by the teacher |
| Code quality (no latch, register initialisation, readability) | 2 | code review |
| F7 report and answers to the questions | 3 | review |
The automatic result does not replace code review: code that passes the testbench can be incomprehensible or fragile.
3. Board Validation Sheet (to be signed by the teacher)
| Lab | Observation required | OK |
|---|---|---|
| F0 | Green LED: 10 beats in 10 s; chaser back and forth at 8 steps/s | [ ] |
| F1 | Each press changes the value by exactly 1, even rapid presses; BTN[2] resets to 0; modulo 32 | [ ] |
| F2 | LED[0]: 2 s "breathing", with no jerks; LED[1] (linear) visibly less smooth | [ ] |
| F3 | Correct echo in a terminal; 1..5 invert the LEDs; ? returns 5 digits + a line feed |
[ ] |
| F4 | Green LED on (PLL locked); top LEDs of the accumulator changing continuously | [ ] |
| F5 | Recording of patterns, looped playback, stop/restart | [ ] |
| F6 | Measurement displayed in the terminal (200–300 ms typically); false start reported | [ ] |
Guide du Cours : Conception Numérique avec Verilog HDL 🎓
Ce document détaille le contenu complet du module pédagogique de 42 heures encadrées (+ 8 h de travail personnel sur projet), destiné aux étudiants de niveau 2ᵉ/3ᵉ année de cycle ingénieur ou licence (génie électrique, informatique industrielle, télécoms, systèmes embarqués).
L'ensemble des outils utilisés est 100 % libre et open-source : Icarus Verilog (simulation), Yosys (synthèse), GTKWave (formes d'onde, optionnel).
📂 Structure du Dépôt
Le pack est organisé de manière modulaire pour faciliter la navigation des enseignants et des étudiants :
| Dossier | Contenu |
|---|---|
00_plan/ |
Fiche de module, planning des 14 séances, modalités d'évaluation, bibliographie |
01_cours/ |
8 chapitres de cours (C1 à C8) |
02_td/ |
5 séries de TD (TDn.md) et leurs corrigés (corriges_TD.md) |
03_tp/ |
9 TP (TP0 à TP8) : enonce.md, src/ (squelette étudiant), tb/ (testbench auto-contrôlé), corrige/ |
04_examens/ |
DS, Examen final, Rattrapage : sujets, fichiers Verilog, testbenches, corrigés et barèmes |
scripts/ |
Scripts bash : run.sh, synth.sh, check_env.sh, test_all.sh |
Makefile |
Raccourcis (make help) |
figures/ |
48 figures (PNG + SVG) : chronogrammes réels, schémas Yosys, diagrammes d'états, graphiques de mesures ; galerie.html pour les parcourir ; make_all.sh pour tout régénérer |
pdf/ |
Versions PDF : polycopié, TD, TP, sujets d'examen, corrigés (enseignant) |
🚀 Démarrage Rapide (Ubuntu / Debian / WSL)
sudo apt update && sudo apt install -y iverilog yosys gtkwave
cd pack_verilog
scripts/check_env.sh # vérifie l'installation
scripts/run.sh 03_tp/TP1_combinatoire src # teste VOTRE code (dossier src/)
scripts/run.sh 03_tp/TP1_combinatoire corrige # teste le corrigé
make help
Chaque testbench affiche une dernière ligne RESULT: PASS ou RESULT: FAIL (n erreurs). Le code de retour du script vaut 0 uniquement en cas de PASS : il peut servir à la notation automatique.
📊 Outils Visuels Intégrés
scripts/wave.sh <fichier.vcd> tb.clk tb.q:dec --grid 10 # chronogramme PNG/SVG (sans GTKWave)
scripts/show.sh <module> <fichier.v> [--gates] # schéma du circuit généré par Yosys (RTL ou portes)
figures/make_all.sh # régénère toutes les figures du pack (graphviz + matplotlib)
Note : Les figures ne sont pas dessinées à la main. Les chronogrammes proviennent de simulations réelles, les schémas de yosys show, les graphiques de mesures Yosys (cellules par module/type, coût des additionneurs et de l'ALU) et d'un modèle de latence du GCD validé sur 400 simulations du RTL.
👨🏫 Guide pour l'Enseignant
-
Validation Automatique : make test (ou scripts/test_all.sh) vérifie que tous les corrigés passent, que tous les squelettes étudiants échouent (testbench non trivial) et que le mutant de la FIFO est détecté.
-
Résultat de validation sur ce pack : "TOUT EST COHÉRENT" (Icarus Verilog 12, Yosys 0.52+).
-
Sécurité des Examens : Ne diffusez pas les dossiers corrige/, mutant/, corriges_TD.md, corrige.md et pdf/enseignant avant la fin des séances concernées.
-
Évaluation : Les 3 examens sont indépendants et de difficulté comparable ; le rattrapage utilise d'autres modules que l'examen final.
-
Étude de Cas GCD : Le GCD du TP8 reprend l'architecture (contrôle/chemin de données, interface req/resp, 8 ports, 54 bits) du rapport Yosys fourni ; le chapitre C8 et le TD4 exploitent les chiffres de ce rapport.
🌐 Écosystème & Support
Ce pack éducatif est développé et optimisé par Zaxam.tech. Si vous cherchez des outils pour automatiser vos flux de conception de puces (LibreLane, OpenROAD), découvrez HiveZe, notre assistant EDA open-source.
- 🌍 Site Web : zaxam.net
- 📧 Contact : contact@zaxam.net
- ☕ Soutenir le projet : Buy me a coffee
- ⭐ GitHub Sponsors : Sponsor Zaxam.tech /Don-zak
Conception numérique et description matérielle en Verilog HDL
Fiche de module et planning pédagogique
1. Fiche de module
| Intitulé | Conception numérique et description matérielle en Verilog HDL |
| Public | Cycle ingénieur / licence appliquée, 2ᵉ–3ᵉ année (GE, GI, télécoms, systèmes embarqués) |
| Volume horaire | 42 h encadrées (19,5 h cours · 7 h TD · 14 h TP · 1,5 h DS) + 8 h de projet en autonomie |
| Crédits / coefficient | 3 ECTS (à adapter) |
| Prérequis | Algèbre de Boole, logique combinatoire et séquentielle (bascules, compteurs), notions d'algorithmique, usage élémentaire du terminal Linux |
| Outils | Icarus Verilog, Yosys, GTKWave (optionnel), bash, make |
| Langue d'enseignement | Français (vocabulaire technique anglais conservé : testbench, netlist, handshake…) |
Objectifs d'apprentissage
À l'issue du module, l'étudiant est capable de :
- Décrire en Verilog (sous-ensemble synthétisable) des circuits combinatoires, séquentiels et des machines à états ;
- Structurer un projet de manière hiérarchique et paramétrable (modules,
parameter,generate) ; - Vérifier un module à l'aide d'un testbench auto-contrôlé, avec modèle de référence et stimuli aléatoires ;
- Synthétiser avec Yosys, lire un rapport (
stat), détecter les erreurs classiques (latch, largeur de bus) ; - Concevoir une unité de traitement avec séparation contrôle / chemin de données (étude de cas GCD) ;
- Automatiser les tests et la synthèse par des scripts bash et un
Makefile.
2. Planning des 14 séances (3 h chacune)
Chaque séance comporte un bloc de cours et un bloc d'application ; l'examen final (2 h) a lieu en semaine 15.
| Séance | Cours (1 h 30) | Application (1 h 30) | Livrable / évaluation |
|---|---|---|---|
| 1 | C1 Flot de conception, HDL, Verilog, simulation | TP0 Prise en main : bash, iverilog, GTKWave | |
| 2 | C2a Types, vecteurs, opérateurs, assign |
TD1 Logique combinatoire | |
| 3 | C2b always @*, if, case, latches |
TP1 Mux, additionneur (hiérarchie) | Test auto TP1 |
| 4 | C2c Arithmétique, largeurs, signé/non signé | TP2 ALU 8 bits, décodeur 7 segments | Test auto TP2 |
| 5 | C3a Bascules, registres, reset, horloge | TD2 Logique séquentielle | |
| 6 | C3b Compteurs, bloquant vs non bloquant | TP3 Compteur, LFSR, détecteur de front | Test auto TP3 |
| 7 | C4a FSM : Moore, Mealy, codage des états | TD3 Machines à états | |
| 8 | C4b FSM : style à 3 blocs, bonnes pratiques | TP4 Détecteur de séquence, distributeur | Test auto TP4 |
| 9 | DS (1 h 30) | C5 Hiérarchie, paramètres, generate, mémoires (1 h 30) |
DS noté |
| 10 | C6a Testbench : horloge, stimuli, $display |
TP5 Additionneur N bits, popcount, banc de registres | Test auto TP5 |
| 11 | C6b Auto-contrôle, scoreboard, mutation | TP6 FIFO + testbench à scoreboard + mutant | Test auto TP6 |
| 12 | C7 Synthèse Yosys, lecture du rapport | TP7 Synthèse, latches, comparaison d'additionneurs | Compte rendu TP7 |
| 13 | C8 Étude de cas : GCD (contrôle/données) | TD4 Lecture d'un rapport Yosys réel | |
| 14 | TP8 Projet GCD (2 h) | TD5 Révisions / sujets types (1 h) | Projet rendu (+ 8 h perso) |
| 15 | Examen final (2 h, machine) | Examen noté | |
| — | Rattrapage (1 h 30, session ultérieure) | Remplace la note d'examen |
Totaux : cours 19,5 h · TD 7 h (TD1 à TD4 : 1 h 30 chacun, TD5 : 1 h) · TP 14 h (TP0–TP7 : 1 h 30 chacun, TP8 : 2 h) · DS 1 h 30 = 42 h.
3. Évaluation
| Composante | Poids | Modalités |
|---|---|---|
| Travaux pratiques | 20 % | Tests automatiques RESULT: PASS (TP1–TP6) + compte rendu TP7 |
| Projet GCD (TP8) | 20 % | Contrôleur + rapport de synthèse + testbench complété ; soutenance de 5 min |
| DS (séance 9) | 20 % | 1 h 30, sur machine, notation automatique + relecture |
| Examen final | 40 % | 2 h, sur machine : partie A écrite (8 pts) + partie B Verilog (12 pts) |
| Rattrapage | Remplace la note de l'examen final ; contrôle continu conservé |
Notation automatique : un script (scripts/run.sh) produit PASS/FAIL et la liste des erreurs. La note
reste à la discrétion de l'enseignant : une relecture du code (lisibilité, absence de latch, style synchrone) est recommandée.
4. Matériel et organisation
- Salle machine avec Linux (ou WSL2 sous Windows) ; installation :
sudo apt install iverilog yosys gtkwave. - Un dossier par étudiant, copie de
pack_verilog/sans les dossierscorrige/. - Dépôt Git conseillé pour le projet (un commit par fonctionnalité).
5. Bibliographie
- S. Palnitkar, Verilog HDL: A Guide to Digital Design and Synthesis, Prentice Hall.
- IEEE Std 1364-2005, Verilog Hardware Description Language.
- D. Harris, S. Harris, Digital Design and Computer Architecture, Morgan Kaufmann.
- C. Cummings, Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill! (SNUG 2000).
- Documentation Yosys : https://yosyshq.readthedocs.io ; Icarus Verilog : https://steveicarus.github.io/iverilog/.
Chapitre 1 — Introduction : du cahier des charges au circuit
Durée : 1 h 30 · Séance 1 · TP associé : TP0
1.1 Objectifs
Situer le langage Verilog dans le flot de conception numérique, installer et utiliser la chaîne d'outils libre.
1.2 Pourquoi un langage de description matérielle (HDL) ?
Un circuit intégré moderne contient de quelques milliers à plusieurs milliards de portes : le schéma manuel n'est plus possible. Un HDL permet de décrire le comportement ou la structure, de le simuler avant fabrication, puis de le synthétiser automatiquement vers des portes logiques (ASIC) ou des blocs configurables (FPGA).
Un HDL n'est pas un langage de programmation : une description Verilog décrit du matériel qui fonctionne en parallèle. Chaque
assign, chaque blocalwaysest un morceau de circuit toujours « actif ».
1.3 Le flot de conception
Ce module couvre les trois premières étapes (RTL, simulation, synthèse logique). Le placement-routage et l'analyse temporelle sont présentés uniquement comme ouverture.
1.4 Niveaux d'abstraction
| Niveau | Exemple | Usage |
|---|---|---|
| Comportemental | always @* y = a + b; |
Modélisation, testbench |
| RTL (Register Transfer Level) | registres + logique entre registres | Niveau de synthèse |
| Structurel | instances de modules / portes | Hiérarchie, netlists |
1.5 Verilog : premières notions
Un module est la brique de base : il a des ports (input, output) et un corps.
module half_adder (
input a, b,
output s, c
);
assign s = a ^ b; // somme
assign c = a & b; // retenue
endmodule
- Verilog est sensible aux majuscules/minuscules ; les commentaires :
//et/* ... */. - Les instructions
assignet les blocsalways/initials'exécutent en parallèle. - Seul un sous-ensemble du langage est synthétisable ; le reste (
initialavec délais,$display,#10…) sert à la simulation et aux testbenches.
1.6 La chaîne d'outils du module
| Outil | Rôle | Commande type |
|---|---|---|
iverilog |
compile les sources pour simulation | iverilog -g2005 -o sim.vvp tb.v dut.v |
vvp |
exécute la simulation | vvp sim.vvp |
gtkwave |
visualise *.vcd |
gtkwave tp0.vcd |
yosys |
synthèse logique | yosys -p "read_verilog dut.v; synth -top dut; stat" |
1.7 Rappels bash indispensables
pwd; ls -l; cd dossier; mkdir -p a/b; cp src dst; mv a b; rm fichier
cat fichier; less fichier; head -n 20 fichier; grep -n "motif" fichier
commande1 | commande2 # tube : sortie de 1 = entrée de 2
commande > log.txt # redirection ; >> pour ajouter
./script.sh && echo OK # enchaînement conditionnel
echo $? # code retour de la dernière commande (0 = succès)
1.7bis Outils visuels du pack
Trois commandes permettent de voir ce que l'on conçoit, sans installer d'interface graphique lourde :
scripts/wave.sh <fichier.vcd> tb.clk tb.q:dec # chronogramme PNG/SVG à partir d'un VCD
scripts/show.sh adder4 src/tp1_comb.v # schéma du circuit (niveau RTL) généré par Yosys
scripts/show.sh ZeroComparator src/x.v --gates # schéma après synthèse (portes)
Le dossier figures/ contient toutes les figures du cours (figures/galerie.html pour les parcourir). Elles sont produites
par de vraies simulations et synthèses : figures/make_all.sh les régénère.
1.8 Points clés à retenir
- Verilog décrit du matériel, tout s'exécute en parallèle.
- Le flot : RTL → simulation → synthèse → implémentation.
- On valide toujours par simulation avant de synthétiser.
- Tous les TP se testent par
scripts/run.sh <dossier> src: une ligneRESULT: PASSconclut la simulation.
Chapitre 2 — Logique combinatoire en Verilog
Durée : 4 h 30 (3 séances de cours, S2 à S4) · TD1, TP1, TP2
2.1 Types de données
wire: fil, piloté parassignou par une sortie de module ;reg: variable affectée dans un bloc procédural (always,initial).regne signifie pas « registre » : selon le bloc, une variableregdevient soit un fil (logique combinatoire), soit une bascule (bloc d'horloge).- Vecteurs :
wire [7:0] bus;(bit 7 = poids fort). Mémoires :reg [7:0] mem [0:15];. - Valeurs à 4 états :
0,1,x(inconnu),z(haute impédance).
2.2 Littéraux
<taille>'<base><valeur> : 4'b1010, 8'hFF, 12'd100, 16'sd-5 (signé). Sans taille : 32 bits (source d'erreurs !).
2.3 Opérateurs
| Famille | Opérateurs | Remarque |
|---|---|---|
| Bit à bit | ~ & \| ^ ~^ |
résultat de même largeur que les opérandes |
| Logiques | ! && \|\| |
résultat 1 bit (vrai/faux) |
| Réduction | &x \|x ^x ~&x |
un seul opérande → 1 bit (ex : ^x = parité) |
| Arithmétiques | + - * / % |
/ et % coûteux ou non synthétisables |
| Décalage | << >> >>> |
>>> arithmétique si l'opérande est signé |
| Comparaison | == != < <= > >= === !== |
===/!== comparent aussi x/z (testbench) |
| Concaténation | {a, b} ; réplication {4{a}} |
{8{1'b0}} = 8'h00 |
| Conditionnel | s ? a : b |
multiplexeur |
2.3bis Largeurs : la règle qui piège tout le monde
En Verilog, la largeur d'une expression est celle du plus grand de ses opérandes et de la cible de l'affectation.
wire [7:0] a, b; wire [8:0] s;
assign s = a + b; // OK : l'addition est faite sur 9 bits, la retenue est conservée
wire [7:0] t = a + b; // retenue perdue (troncature silencieuse)
assign s = {1'b0, a} + {1'b0, b}; // explicite, recommandé
2.4 Description par flot de données : assign
module mux2 #(parameter W = 8) (input [W-1:0] a, b, input s, output [W-1:0] y);
assign y = s ? b : a;
endmodule
2.5 Description comportementale : always @*
Pour les if/case, on utilise un bloc procédural sensible à toutes ses entrées : always @*.
module dec2to4 (input [1:0] a, input en, output reg [3:0] y);
always @* begin
y = 4'b0000; // valeur par défaut
if (en) case (a)
2'd0: y = 4'b0001;
2'd1: y = 4'b0010;
2'd2: y = 4'b0100;
2'd3: y = 4'b1000;
endcase
end
endmodule
Règles : affectations bloquantes (=) dans un bloc combinatoire ; chaque sortie reçoit une valeur
dans tous les cas (valeur par défaut en tête de bloc, ou default: / else final).
2.6 Le piège du latch inféré
Si une variable n'est pas affectée dans tous les chemins d'un bloc always @*, le synthétiseur doit
mémoriser l'ancienne valeur : il crée un latch, non voulu.
always @* if (en) y = a; // MAUVAIS : latch (y mémorisé quand en = 0)
always @* begin y = 1'b0; if (en) y = a; end // BON
Yosys signale le latch ($_DLATCH_), scripts/synth.sh affiche alors une alerte (TP7).
2.7 case, casez, priorité
if / else if crée une priorité (chaîne), case un multiplexage parallèle. casez accepte ? comme
joker (casez (r) 4'b1???: ...). Toujours terminer par default.
2.8 Fonctions
function [3:0] popcnt8 (input [7:0] x);
integer i;
begin popcnt8 = 0; for (i = 0; i < 8; i = i + 1) popcnt8 = popcnt8 + x[i]; end
endfunction
Une function est combinatoire, sans délai ; une boucle for est dépliée à la synthèse.
2.9 Arithmétique signée
Déclarer signed pour les nombres en complément à 2 : wire signed [7:0] a;. Mélanger signé et non signé
dans une même expression ⇒ tout est interprété non signé. Pour étendre le signe : {{4{a[3]}}, a}.
2.10 Points clés
- Un bloc combinatoire =
always @*+=+ toutes les sorties affectées dans tous les cas. - Attention aux largeurs et aux littéraux sans taille.
xen simulation = signal non initialisé ou conflit : à traquer.- Latch inféré = presque toujours une erreur de description.
Chapitre 3 — Logique séquentielle synchrone
Durée : 3 h (S5–S6) · TD2, TP3
3.1 Principe synchrone
Tout l'état du circuit est stocké dans des bascules D commandées par une même horloge. Entre deux fronts, la logique combinatoire calcule l'état suivant ; au front, il est mémorisé. Contraintes physiques : temps de setup (donnée stable avant le front) et de hold (stable après), vérifiées par l'analyse temporelle (STA), pas par la simulation fonctionnelle.
3.2 Le bloc d'horloge
always @(posedge clk) begin
q <= d; // affectation NON bloquante
end
Un bloc always @(posedge clk) décrit des bascules : chaque reg affecté dedans devient un registre.
3.3 Reset
Synchrone (convention de ce cours : actif à 1, évalué au front d'horloge) :
always @(posedge clk) if (rst) q <= 8'd0; else q <= d;
Asynchrone (agit immédiatement, indépendamment de l'horloge) :
always @(posedge clk or posedge rst) if (rst) q <= 8'd0; else q <= d;
Le reset synchrone se prête mieux aux FPGA et à l'analyse temporelle ; l'asynchrone est courant en ASIC (prévoir alors une désactivation synchronisée). Ne jamais mélanger les deux styles dans un même projet sans raison.
3.4 Registre avec validation (enable)
always @(posedge clk) if (en) q <= d; // synthétisé : bascule avec enable ($_DFFE_PP_ chez Yosys)
Ne jamais « gater » l'horloge à la main (clk & en) : utiliser un enable.
3.5 Affectations bloquantes vs non bloquantes — LA règle d'or
| Bloc d'horloge (séquentiel) | Bloc always @* (combinatoire) |
|
|---|---|---|
| Opérateur | <= (non bloquant) |
= (bloquant) |
Exemple révélateur (registre à décalage 3 étages) :
always @(posedge clk) begin q1 <= d; q2 <= q1; q3 <= q2; end // BON : 3 bascules en série
always @(posedge clk) begin q1 = d; q2 = q1; q3 = q2; end // MAUVAIS : q3 = d, une seule bascule effective
Avec <=, toutes les valeurs à droite sont lues avant le front, puis toutes les mises à jour sont
appliquées « en même temps » : c'est le comportement d'un vrai registre.
Autres règles : un reg n'est affecté que dans un seul bloc always ; ne pas mélanger = et <= dans un même bloc.
3.6 Compteurs et registres classiques
module counter #(parameter W = 4) (input clk, rst, en, output reg [W-1:0] q);
always @(posedge clk) begin
if (rst) q <= {W{1'b0}};
else if (en) q <= q + 1'b1; // débordement naturel : modulo 2^W
end
endmodule
Registre à décalage : sh <= {sh[W-2:0], din}; ; LFSR : décalage + XOR de bits de rétroaction (TP3).
3.7 Style en deux blocs : registre + logique d'état suivant
reg [3:0] state, next;
always @(posedge clk) if (rst) state <= 4'd0; else state <= next; // séquentiel
always @* next = state + 1'b1; // combinatoire
Ce découpage structure le code et sera généralisé aux FSM (chapitre 4).
3.8 Signaux asynchrones et métastabilité
Un signal externe non synchronisé (bouton, autre domaine d'horloge) peut violer setup/hold et rendre la bascule métastable. Remède de base : synchroniseur à deux bascules.
reg s1, s2;
always @(posedge clk) begin s1 <= async_in; s2 <= s1; end // utiliser s2
3.9 Points clés
- Séquentiel :
always @(posedge clk)+<=. - Un style de reset unique et clairement documenté.
if (en)= enable, pas de gating manuel d'horloge.- Tout signal asynchrone entrant est resynchronisé.
Chapitre 4 — Machines à états finis (FSM)
Durée : 3 h (S7–S8) · TD3, TP4
4.1 Modèles
Une FSM est définie par un ensemble d'états, une fonction d'état suivant et une fonction de sortie.
- Moore : sortie = f(état). Sortie stable, synchrone, décalée d'un cycle.
- Mealy : sortie = f(état, entrées). Réaction immédiate, mais dépend des entrées (risque de parasites, chemins combinatoires entrée→sortie).
4.2 Style recommandé : trois blocs
module seq_moore (input clk, rst, in, output out); // détecteur de "1011" avec chevauchement
localparam S0 = 3'd0, S1 = 3'd1, S10 = 3'd2, S101 = 3'd3, S1011 = 3'd4;
reg [2:0] state, next;
always @(posedge clk) // (1) registre d'état
if (rst) state <= S0; else state <= next;
always @* begin // (2) état suivant
next = state; // valeur par défaut : on reste
case (state)
S0: next = in ? S1 : S0;
S1: next = in ? S1 : S10;
S10: next = in ? S101 : S0;
S101: next = in ? S1011 : S10;
S1011: next = in ? S1 : S10;
default: next = S0; // états inutilisés -> retour sûr
endcase
end
assign out = (state == S1011); // (3) sortie (Moore)
endmodule
Pour la version Mealy, la sortie devient assign out = (state == S101) & in; et l'état S1011 disparaît.
4.3 Méthode de conception
- Lister les états en nommant ce que chacun mémorise.
- Dessiner le diagramme (états, transitions étiquetées par les entrées, sorties).
- Vérifier complétude (toutes les entrées traitées à chaque état) et exclusivité des transitions.
- Coder en trois blocs, avec
defaultet valeur par défaut denext. - Tester avec un modèle de référence et des séquences aléatoires.
4.4 Codage des états
| Codage | Bits pour N états | Avantage | Usage |
|---|---|---|---|
| Binaire | ⌈log₂ N⌉ | peu de bascules | petites FSM |
| One-hot | N | logique d'état suivant simple, rapide | FPGA, grosses FSM |
| Gray | ⌈log₂ N⌉ | 1 seul bit change par transition | compteurs, traversée d'horloges |
Yosys peut ré-encoder automatiquement une FSM (fsm dans synth), à condition de la détecter.
4.5 Bonnes pratiques
- Toujours prévoir un reset vers un état initial défini.
- Toutes les sorties assignées dans tous les états (valeurs par défaut) : pas de latch.
- Nommer les états avec
localparam; éviter les nombres magiques. - Si une sortie Mealy alimente un registre dans un autre module, penser à la chaîne de chemin combinatoire.
- Interfaces val/rdy (handshake) : un transfert a lieu quand
val && rdyau front d'horloge (voir GCD, chapitre 8).
4.6 Points clés
- Moore vs Mealy : latence d'un cycle contre dépendance aux entrées.
- Trois blocs : registre, état suivant, sorties.
defaultet valeurs par défaut partout.
Chapitre 5 — Hiérarchie, paramètres et génération
Durée : 1 h 30 (S9) · TP5
5.1 Instanciation de modules
adder4 u_add (.a(x), .b(y), .cin(1'b0), .s(sum), .cout(co)); // association PAR NOM (recommandée)
L'association par position (adder4 u (x, y, 1'b0, sum, co)) est fragile : un ordre de ports modifié casse silencieusement le circuit.
Un port non connecté doit l'être explicitement : .cout(). Le nom d'instance (u_add) est obligatoire.
5.2 Paramètres
module counter #(parameter W = 8, parameter MAXV = 255) (...);
counter #(.W(12), .MAXV(4000)) u_c (...); // surcharge à l'instanciation
parameter: modifiable de l'extérieur ;localparam: constante interne (ex :localparam AW = $clog2(DEPTH);).$clog2(n): ⌈log₂ n⌉, utile pour dimensionner des compteurs et des adresses.
5.3 generate
Répétition ou instanciation conditionnelle à l'élaboration (avant simulation/synthèse).
genvar i;
generate
for (i = 0; i < N; i = i + 1) begin : g_bit // le nom du bloc est obligatoire
fa1 u_fa (.a(a[i]), .b(b[i]), .cin(c[i]), .s(s[i]), .cout(c[i+1]));
end
endgenerate
generate if (FAST) ... else ... choisit une architecture selon un paramètre.
5.4 Mémoires
reg [7:0] mem [0:255]; // 256 mots de 8 bits
always @(posedge clk) if (we) mem[waddr] <= wdata; // écriture synchrone
assign rdata = mem[raddr]; // lecture asynchrone (ou registrée pour une RAM de FPGA)
initial $readmemh("init.hex", mem); // initialisation (simulation / FPGA)
Une grosse mémoire est mappée sur de la RAM dédiée du FPGA ; en ASIC on utilise un compilateur de mémoire (macro).
5.5 Organisation d'un projet
- Un module par fichier, nom de fichier = nom du module ;
- un module de plus haut niveau (top) qui ne fait que connecter ;
- séparer chemin de données (registres, opérateurs) et contrôle (FSM) — voir chapitre 8 ;
- dossiers
src/,tb/,scripts/; unMakefilepour tout automatiser.
5.6 Points clés
- Instanciation par nom, paramètres surchargés par nom.
generate= répétition de matériel, pas boucle d'exécution.- Hiérarchie claire = code testable module par module.
Chapitre 6 — Vérification : écrire un bon testbench
Durée : 3 h (S10–S11) · TP5, TP6
6.1 Structure d'un testbench
Un testbench est un module sans port qui instancie le DUT (Device Under Test), génère les stimuli et vérifie les sorties.
`timescale 1ns/1ps
module tb;
reg clk = 0, rst = 1; reg [7:0] d; wire [7:0] q;
always #5 clk = ~clk; // horloge de période 10 ns
my_reg dut (.clk(clk), .rst(rst), .d(d), .q(q));
initial begin
$dumpfile("tb.vcd"); $dumpvars(0, tb); // formes d'onde pour GTKWave
repeat (3) @(negedge clk); rst = 0;
...
$finish;
end
endmodule
6.2 Génération de stimuli et synchronisation
- Délai :
#10;; attente d'événement :@(posedge clk),@(negedge clk),wait (cond). - Bonne pratique anti-race : appliquer les entrées sur le front descendant (
@(negedge clk)) et échantillonner sur le front montant : le DUT voit des entrées stables au front actif. - Aléatoire :
$random(32 bits signé) ;{$random} % Npour un entier positif ; graine :$random(seed). - Fichiers :
$readmemh("vecteurs.hex", tab). task: sous-programme avec délais autorisés (envoi d'une trame, transaction…).
6.3 Auto-contrôle (self-checking)
Regarder les formes d'onde à l'œil ne passe pas à l'échelle et ne peut pas être automatisé. Un bon testbench :
- calcule le résultat attendu avec un modèle de référence (fonction comportementale, indépendante du DUT) ;
- compare avec
!==(qui détecte aussix/z, contrairement à!=) ; - compte les erreurs et termine par un verdict machine-lisible :
if (errors == 0) $display("RESULT: PASS"); else $display("RESULT: FAIL (%0d erreurs)", errors);
$finish;
Les testbenches du pack respectent cette convention : scripts/run.sh renvoie le code 0 uniquement en cas de PASS.
6.4 Scoreboard et vérification aléatoire
Le scoreboard est un modèle de référence mis à jour en parallèle du DUT et comparé à chaque cycle (TP6 : FIFO de référence en tableau circulaire). Combiner : * tests dirigés : cas limites (plein, vide, 0, valeur max, débordement) ; * tests aléatoires : grand nombre de cycles, plusieurs profils (écritures fréquentes, lectures fréquentes, rafales).
6.5 Qualité de la vérification : le test de mutation
Comment savoir si un testbench est bon ? On injecte volontairement un bug (mutant) dans le DUT ;
un bon testbench doit échouer. Le TP6 fournit mutant/fifo_sync.v (FIFO déclarée pleine un mot trop tôt) :
scripts/run.sh 03_tp/TP6_testbench_fifo mutant doit afficher FAIL.
6.6 Couverture (ouverture)
Couverture de lignes, de branches, d'états de FSM, fonctionnelle. Verilator et les simulateurs commerciaux fournissent des outils de couverture ; l'idée : mesurer ce que les tests ont réellement exercé.
6.7 Erreurs classiques de testbench
- Oublier
$finish→ simulation infinie (l'horloge ne s'arrête jamais) ; prévoir un chien de garde (timeout). - Comparer avec
!=au lieu de!==: unxpasse inaperçu. - Piloter le DUT sur le front actif : conditions de course (race condition).
- Modèle de référence copié du DUT : il reproduit les mêmes erreurs ; l'écrire indépendamment (autre algorithme, vue spec).
6.8 Points clés
- Testbench = DUT + stimuli + modèle de référence + verdict automatique.
- Entrées sur
negedge, observation après le front. - Évaluer le testbench par mutation.
Chapitre 7 — Synthèse logique avec Yosys
Durée : 1 h 30 (S12) · TP7, TD4
7.1 Qu'est-ce que la synthèse ?
Transformer une description RTL en un réseau de portes (netlist) équivalent, optimisé pour une cible
(FPGA ou bibliothèque de cellules ASIC). Yosys est un synthétiseur open source ; son script synth enchaîne
des passes élémentaires.
7.2 Les passes principales de synth -top <module>
| Passe | Rôle |
|---|---|
hierarchy |
construit la hiérarchie à partir du module top, supprime les modules inutilisés |
proc |
convertit les blocs always/if/case en multiplexeurs et bascules ; détecte les latches (proc_dlatch) |
opt / opt_expr |
simplifications logiques, propagation de constantes, suppression de logique morte |
fsm |
détecte et ré-encode les machines à états |
memory |
infère des mémoires |
techmap |
remplace les opérateurs (+, <, …) par des portes élémentaires |
abc |
optimise et projette la logique sur un jeu de portes génériques |
stat |
affiche les statistiques (cellules, fils, hiérarchie) |
Commande utilisée dans ce module :
yosys -p "read_verilog gcd.v; synth -top gcd; stat"
# ou, avec notre script : scripts/synth.sh gcd fichier1.v fichier2.v
7.3 Lire un rapport stat
Chaque ligne Number of cells est suivie du détail par type de cellule. Les cellules logiques génériques de Yosys :
| Cellule | Signification |
|---|---|
$_AND_, $_OR_, $_XOR_, $_XNOR_, $_NOT_, $_NAND_, $_NOR_ |
portes à 2 entrées (1 entrée pour NOT) |
$_ANDNOT_, $_ORNOT_ |
A & ~B, A \| ~B (portes avec une entrée inversée) |
$_MUX_ |
multiplexeur 2 vers 1 |
$_DFF_P_ |
bascule D, front montant |
$_DFFE_PP_ |
bascule D avec enable (P = horloge sur front montant, P = enable actif haut) |
$_SDFF_PP0_ |
bascule avec reset synchrone (clk P, reset actif haut, valeur de reset 0) |
$_DLATCH_P_ |
latch : presque toujours un bug |
Avec -top, le rapport est présenté par module, puis une rubrique design hierarchy donne le cumul
sur l'ensemble de la hiérarchie (nombre d'instances × contenu).
Attention :
statsans bibliothèque compte des cellules génériques, pas des mm² ni des nanosecondes. Pour la surface réelle, on fournit une bibliothèque.lib(stat -liberty cells.lib) ; pour le temps de chemin critique, on utilise un outil de STA (par exemple OpenSTA). Le nombre de cellules est un indicateur relatif utile pour comparer deux architectures.
7.4 Exemple : « 16 bits égal à zéro »
Le rapport de l'étude de cas (chapitre 8) indique pour ZeroComparator 16 bits : 15 cellules
(3 $_ANDNOT_, 1 $_NOR_, 11 $_OR_). C'est un arbre de réduction : un OU de 16 bits nécessite 15 portes à
2 entrées (n − 1). Interprétation d'un résultat : on le relie toujours à la structure attendue.
7.5 Erreurs détectées à la synthèse
- Latch inféré (
if/caseincomplet) →$_DLATCH_dansstat; messageLatch inferreddans le journal. - Largeur de bus incohérente (avertissements
Resizing,Warning: ... width). - Signal jamais piloté (
undriven), boucle combinatoire. initialavec valeur : accepté pour les FPGA seulement ; à éviter en RTL générique.
7.6 Simulation post-synthèse
yosys -p "read_verilog gcd.v; synth -top gcd; write_verilog -noattr gcd_syn.v"
iverilog -g2005 -o gl.vvp tb_gcd.v gcd_syn.v && vvp gl.vvp # même testbench, netlist de portes
Le même testbench doit passer sur la netlist : c'est une vérification d'équivalence par simulation (la preuve formelle, plus rigoureuse, est hors programme).
7.7 Points clés
proc→opt→fsm/memory→techmap→abc→stat.- Lire un rapport : types de bascules, nombre de cellules par module, hiérarchie.
- Zéro latch dans un code synchrone propre.
Chapitre 8 — Étude de cas : unité de calcul du PGCD (GCD)
Durée : 1 h 30 (S13) · TD4, TP8 (projet)
8.1 Cahier des charges
Calculer le plus grand commun diviseur de deux entiers 16 bits A et B par l'algorithme d'Euclide (soustractions et échanges), avec une interface à poignée de main :
- requête :
req_val,req_rdy,req_msg[31:0] = {A[15:0], B[15:0]}; - réponse :
resp_val,resp_rdy,resp_msg[15:0]; clk,reset: au total 8 ports, 54 bits (1+1+32+1+1+16+1+1).
Un transfert a lieu à un front d'horloge où val et rdy valent 1 simultanément.
8.2 Algorithme
tant que B ≠ 0 :
si A < B : échanger A et B
sinon : A ← A − B
résultat : A
Cas limites : gcd(a, 0) = a ; gcd(0, b) = b (un échange suffit) ; gcd(0, 0) = 0.
8.3 Architecture contrôle / chemin de données
- Chemin de données : 2 registres 16 bits avec enable (A, B), un multiplexeur 3 voies (entrée / A−B / B)
pour A, un multiplexeur 2 voies (entrée / A) pour B, un soustracteur, un comparateur
A<B, un détecteurB=0. - Contrôleur : FSM 3 états (registre d'état de 2 bits avec reset synchrone).
| État | Sorties | Transition |
|---|---|---|
| IDLE | req_rdy=1, charge A et B depuis req_msg |
req_val → CALC |
| CALC | si B≠0 : échange (si A<B) sinon A←A−B |
B=0 → DONE |
| DONE | resp_val=1, resp_msg = A |
resp_rdy → IDLE |
8.4 Vérification
tb_gcd.v : fonction de référence d'Euclide (modulo), cas limites ((0,0), (a,0), (0,b), (65535,1)…),
150 cas aléatoires et contre-pression aléatoire sur resp_rdy ; contrôle du maintien de resp_val tant que
resp_rdy est bas.
8.5 Analyse du rapport Yosys (exécution synth -top gcd; stat)
Le rapport de référence de l'étude porte sur une version générée automatiquement du GCD (même architecture). Chiffres relevés :
| Module | Cellules | Remarque |
|---|---|---|
Subtractor 16 bits |
98 | plus gros bloc (≈ 30 % du total) |
LtComparator 16 bits |
72 | comparateur de magnitude |
Mux 3 voies (16 bits) |
67 | $_MUX_ + logique |
Mux 2 voies (16 bits) |
16 | 16 $_MUX_ |
RegEn (×2) |
2 × 16 | 16 × $_DFFE_PP_ chacun |
ZeroComparator |
15 | arbre de 15 portes (n − 1) |
RegRst (état) |
2 | 2 × $_SDFF_PP0_ |
| Contrôleur (logique seule) | 26 | |
| Total (hiérarchie) | 328 | dont 34 bascules (32 $_DFFE_PP_ + 2 $_SDFF_PP0_) |
Vérification : 98 + 72 + 67 + 16 + 32 + 15 + (26 + 2) = 328 cellules. Le nombre de bascules (34) correspond à l'architecture : 16 (A) + 16 (B) + 2 (état).
Le GCD du pack, réécrit à la main avec la même hiérarchie, donne environ 341 cellules après synth -top gcd :
l'écart de quelques pourcents est normal (style de description différent, optimisation ABC) ; l'architecture et
le nombre de bascules (34) sont identiques. Plus important que le total : identifier quel bloc domine et
pourquoi.
8.6 Pistes d'optimisation (projet, bonus)
- Supprimer le comparateur en réutilisant le bit de signe de la soustraction (
A − Bsur 17 bits). - Remplacer l'échange par un calcul de
|A − B|(algorithme de Stein, binaire) : décalages au lieu de soustractions répétées. - Comparer les rapports
statavant/après ; vérifier quetb_gcdpasse toujours.
Latence : un calcul dont la durée dépend des données
Chaque soustraction ou échange coûte un cycle. Pour deux nombres aléatoires de 16 bits la latence typique est d'environ 50 cycles, mais
le pire cas gcd(65535, 1) demande 65 535 opérations. Le graphique ci-dessous est établi sur 20 000 paires avec un modèle validé
sur 400 simulations du RTL (écart constant de 1 cycle pour la poignée de main).
8.7 Points clés
- Séparer contrôle et données rend le code lisible, testable et réutilisable.
- L'interface val/rdy est un contrat ; le testbench doit le vérifier, pas seulement le résultat.
- On valide par simulation, puis on synthétise, on lit le rapport et on re-simule la netlist.
Travaux Pratiques sur Carte FPGA — iCEBreaker 🎓
Ce module autonome de travaux pratiques (27 heures) vient en complément d'un cours de conception numérique en Verilog (il suppose acquises les bases : modules, always, machines à états, testbench).
Matériel requis : une carte iCEBreaker (FPGA Lattice iCE40UP5K, horloge 12 MHz, USB/FTDI) et son Pmod « LED & boutons » (5 LED + 3 boutons). Logiciels (Linux / WSL2) : Icarus Verilog, Yosys, nextpnr-ice40, IceStorm (icepack, iceprog).
sudo apt update && sudo apt install -y iverilog yosys nextpnr-ice40 fpga-icestorm gtkwave
🧪 Les 7 Labs Pratiques
| Lab | Thème | Notion FPGA mise en avant |
|---|---|---|
| F0 | Prise en main : clignotant + chenillard | Flot complet, contraintes, pas de reset (initialisation des registres), rapport de ressources |
| F1 | Boutons mécaniques | Entrée asynchrone, synchroniseur, filtre anti-rebond à compteur saturant |
| F2 | PWM et « respiration » d'une LED | Mémoire bloc (BRAM) inférée, ROM initialisée par fichier, correction gamma |
| F3 | Terminal série USB | UART RX, échantillonnage au milieu du bit, tolérance d'horloge |
| F4 | Fréquence, PLL et DSP | Fermeture de timing, lecture d'un chemin critique, PLL 12→48 MHz, bloc DSP |
| F5 | Séquenceur à mémoire | RAM double accès, latence de lecture, FSM de contrôle |
| F6 | Projet : jeu de réflexes | Intégration, millisecondes, aléa, liaison série, piège de la division |
| F7 | Validation sur carte | Mesures, rapport, présentation |
🚀 Utilisation (Commandes)
scripts/fpga.sh sim F1_entrees_boutons src # simulation de VOTRE code (RESULT: PASS ?)
scripts/fpga.sh all F1_entrees_boutons src # simulation + synthèse + routage + bitstream + vérifications
scripts/fpga.sh prog F1_entrees_boutons src # programme la carte en SRAM (perdu à la mise hors tension)
scripts/fpga.sh flash F1_entrees_boutons src # programme la mémoire flash (persistant)
Chaque lab se valide en trois temps : simulation (RESULT: PASS), flot de synthèse (fréquence et ressources conformes) puis vérification sur la carte (liste de contrôle dans chaque énoncé).
⚠️ État de Validation & Limites
Validé : Les corrigés des 7 labs réussissent simulation + synthèse + placement-routage + génération du bitstream. Les squelettes étudiants échouent (scripts/selftest.sh : TOUT EST COHÉRENT). Outils : Icarus Verilog 12, Yosys 0.33, nextpnr-ice40 0.6.
Limite importante : Ce pack n'a pas été exécuté sur une carte physique (aucune carte disponible lors de sa production). Les broches du fichier board/icebreaker.pcf sont reprises de la documentation publique de la carte et doivent être contrôlées par l'enseignant sur une carte réelle avant la première séance (voir le guide de la carte).
🌐 Écosystème & Support
Ce module FPGA fait partie du Pack Pédagogique Open Source développé par Zaxam.tech.
- 🌍 Site Web : zaxam.net
- 🛠️ Notre outil EDA : HiveZe (Assistant IA).
- 📧 Contact académique : contact@zaxam.net
- 💖 Soutenir le projet :
- ☕ Buy me a coffee
- ⭐ GitHub Sponsors : Sponsor Zaxam.tech / Don-zak
Guide de la carte iCEBreaker et de la chaîne d'outils
1. La carte
| Élément | Broche (SG48) | Niveau actif |
|---|---|---|
Horloge 12 MHz (CLK) |
35 | — |
LED rouge embarquée (LEDR_N) |
11 | allumée si 0 |
LED verte embarquée (LEDG_N) |
37 | allumée si 0 |
Bouton embarqué (BTN_N) |
10 | appuyé = 0 |
Pmod : LED[0] … LED[4] |
26, 27, 25, 23, 21 | allumée si 1 |
Pmod : BTN[0] … BTN[2] |
20, 19, 18 | appuyé = 1 |
UART : RX (entrée FPGA) / TX (sortie FPGA) |
6 / 9 | repos = 1 |
À vérifier avant tout. Ces numéros de broches sont ceux publiés pour la carte et son Pmod « LED & boutons » branché sur le connecteur PMOD2, mais le pack n'a pas pu être testé sur matériel. Comparez
board/icebreaker.pcfau fichier officiel du dépôt de la carte et à la sérigraphie de votre module avant de programmer. Une erreur de broche ne produit en général qu'un montage qui « ne fait rien », mais ne reliez jamais de source externe sans contrôler les tensions (les entrées/sorties du FPGA sont en 3,3 V).
2. Chaîne d'outils
| Étape | Outil | Rôle | Résultat |
|---|---|---|---|
| Simulation | iverilog, vvp |
exécute le testbench | RESULT: PASS / FAIL |
| Synthèse | yosys (synth_ice40) |
RTL → LUT, bascules, BRAM, DSP | top.json, rapport de cellules |
| Placement-routage | nextpnr-ice40 |
place et câble ; analyse temporelle | top.asc, Fmax, taux d'occupation |
| Bitstream | icepack |
convertit .asc |
top.bin |
| Programmation | iceprog |
envoie vers la carte | SRAM (-S) ou flash |
scripts/fpga.sh enchaîne ces étapes ; les fichiers intermédiaires sont dans build_src/ ou build_corrige/ de chaque lab.
Le script ne contraint que les broches réellement utilisées par le module de plus haut niveau.
3. Programmation
fpga.sh prog: configuration volatile (SRAM) : rapide, idéale en TP ; la carte oublie tout à la mise hors tension.fpga.sh flash: écrit la mémoire flash : le montage redémarre seul.- Droits USB (Linux) : si
iceprogrépond « Can't find iCE FTDI USB device », créer la règle udev suivante puis rebrancher :
echo 'ACTION=="add", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6010", MODE:="666"' | sudo tee /etc/udev/rules.d/53-lattice-ftdi.rules
sudo udevadm control --reload-rules && sudo udevadm trigger
- WSL2 : le port USB n'est pas visible par défaut : utiliser
usbipd(côté Windows) pour attacher la carte. - Le circuit FTDI expose deux voies : l'une sert à la programmation, l'autre au port série (souvent
/dev/ttyUSB1). Terminal :screen /dev/ttyUSB1 115200(quitter : Ctrl-A puis K) ; ouscripts/serial_check.py /dev/ttyUSB1pour le lab F3.
4. Particularités d'un FPGA pour l'étudiant venant de la simulation
- Pas de reset sur la carte : les registres reçoivent leur valeur à la configuration : les initialiser à leur déclaration
(
reg [7:0] r = 0;). C'est accepté par Yosys pour l'iCE40 ; ce n'est pas portable vers tous les circuits. - Le FPGA n'est pas un processeur : un module « toujours actif » consomme des ressources en permanence.
- Le temps se compte en cycles : 12 MHz → 83,3 ns par cycle ; 1 s = 12 000 000 cycles (24 bits de compteur).
- La simulation ne suffit pas : une description correcte peut être trop lente (Fmax) ou trop grosse ; seul le placement-routage le dit.
- Les ressources spécialisées (BRAM, DSP, PLL) s'obtiennent par un style d'écriture précis ou par instanciation.
5. Dépannage
| Symptôme | Cause probable | Action |
|---|---|---|
iceprog : périphérique introuvable |
règle udev, câble de charge seule, WSL | voir §3 |
Rien ne se passe après prog |
broches du .pcf, niveaux actifs, mauvaise horloge |
relire §1 ; allumer la LED verte avec LEDG_N = 0 |
| LED inversée | niveau actif mal compris | LED embarquées actives à 0 ; LED du Pmod actives à 1 |
| Boutons « nerveux » | pas de filtrage | F1 |
| Caractères série illisibles | débit ou voie FTDI incorrects | 115200 8N1 ; voie B |
nextpnr : FAIL à X MHz |
chemin combinatoire trop long | F4 : pipeline, DSP |
Progression, évaluation et validation sur carte
1. Planning proposé (27 h)
| Séance | Durée | Lab | Objectif | Livrable |
|---|---|---|---|---|
| 1 | 3 h | F0 | Chaîne complète, première configuration de la carte | RESULT: PASS + vidéo/photo de la carte |
| 2 | 3 h | F1 | Entrées mécaniques fiables | Test + validation carte |
| 3 | 3 h | F2 | PWM, BRAM, ROM | Test + validation carte |
| 4 | 3 h | F3 | Terminal série | Test + serial_check.py |
| 5 | 3 h | F4 | Fréquence, PLL, DSP | Tableau des trois Fmax |
| 6 | 3 h | F5 | RAM et séquenceur | Test + validation carte |
| 7–8 | 6 h | F6 | Projet jeu de réflexes | Test + démonstration |
| 9 | 3 h | F7 | Mesures, rapport, présentation | Rapport + oral |
2. Barème indicatif (/20)
| Critère | Points | Mesure |
|---|---|---|
Simulation : testbench PASS sur les labs F0–F6 |
6 | automatique (fpga.sh sim) |
Flot : synthèse, routage et Fmax conformes (fpga.sh all) |
4 | automatique |
| Démonstration sur carte (liste de contrôle de chaque lab) | 5 | observation par l'enseignant |
| Qualité du code (pas de latch, initialisation des registres, lisibilité) | 2 | relecture |
| Rapport F7 et réponses aux questions | 3 | relecture |
Le résultat automatique ne remplace pas la relecture : un code qui passe le testbench peut être incompréhensible ou fragile.
3. Fiche de validation sur carte (à signer par l'enseignant)
| Lab | Observation demandée | OK |
|---|---|---|
| F0 | LED verte : 10 battements en 10 s ; chenillard aller-retour à 8 pas/s | [ ] |
| F1 | Chaque appui change la valeur d'exactement 1, même appuis rapides ; BTN[2] remet à 0 ; modulo 32 | [ ] |
| F2 | LED[0] : « respiration » de 2 s, sans à-coups ; LED[1] (linéaire) visiblement moins régulière | [ ] |
| F3 | Écho correct dans un terminal ; 1..5 inversent les LED ; ? renvoie 5 chiffres + saut de ligne |
[ ] |
| F4 | LED verte allumée (PLL verrouillée) ; LED du haut de l'accumulateur en évolution continue | [ ] |
| F5 | Enregistrement de motifs, relecture en boucle, arrêt/redémarrage | [ ] |
| F6 | Mesure affichée dans le terminal (200–300 ms typiquement) ; faux départ signalé | [ ] |