You are on page 1of 56

Hardware Description Language:

Verilog

Franco Curotto

Departamento de Ingenierı́a Eléctrica


Facultad de Ciencias Fı́sicas y Matemáticas
Universidad de Chile

2019

Franco Curotto (DIE - U de Chile) Verilog 2019 1 / 37


¿Qué hacemos en Calán?
ROACH2: Reconfigurable Open Architecture Computing Hardware

ADC: EV8AQ160 QUAD


I 5 GSPS
I 8 bit samples

FPGA: Xilinx Virtex-6


I > 400 000 Logic Cells
I 2016 Digital Signal
Processing (DSP) Slices
I 38 304 Kb Block RAM

Franco Curotto (DIE - U de Chile) Verilog 2019 2 / 37


¿Qué hacemos en Calán?
Wideband Spectrometers
in_reg d Z^-2 q [a:b] [cnt_rst] in_reg d Z^-2 q [a:b] [filter_on]
Configuration Blocks
cnt_rst Latency = 2 filter_on Latency = 2
System 1input:uf32.0 = 32 bits 1input:uf32.0 = 32 bits
Generator
in_reg d Z^-2 q [acc_len] in_reg d Z^-2 q reinterpret [filter_gain]

acc_len Latency = 2 filter_gain Latency = 2


1input:uf32.0 = 32 bits 1input:uf32.0 = 32 bits

MSSGE sync_out [sync_out] in_reg d Z^-2 q [filter_acc] in_reg d Z^-2 q [a:b] [channel]
ROACH2
sync_gen filter_acc Latency = 2 channel Latency = 2
XSG_core_config sim_sync_period=12288 1input:uf32.0 = 32 bits 1input:uf32.0 = 32 bits

-2 sync
z
[acc_len] acc_len
[sync_out] -2 d Z^-1 q sync sync_out 8191 shift sync_out -2 -5 -2 d Z^-2 q -5 d Z^-1 q sync new_acc d Z^-1 q d Z^-2 q rst
z z z z z
[cnt_rst] rst
en
++
pipeline20 -2 Latency = 2 Latency = 1 Latency = 1 Latency = 2
z acc_cntrl0
a0 In1 Out1 d Z^-1 =q1
Latency pol1_in1 pol1_out1 in00 addr
X >> 2 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
pipeline19 -2 out00 -2 -5 -2 d Z^-2 q c Z^-5power d Z^-1 q -1 d Z^-1 q din valid d Z^-2 q we
z z z z z Latency =1 Latency =2
a1 In2 Out2 d Z^-1 =q1 pol1_in2 pol1_out2 in01 Latency = 1
Latency X >> 2 Latency = 2 Latency = 1 simple_bram_vacc0_0 Latency = 2 dout0_0
pipeline18 -2 addr
z
a2 In3 Out3 d Z^-1 =q1 pol1_in3 pol1_out3 in02 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
Latency X >> 2 -2 -5 -2 -1 d Z^-1 q d Z^-2 q
out01 z z z d Z^-2 q c Z^-5power d Z^-1 q z Latency =1 din valid Latency =2 we
pipeline17 -2
z Latency = 1 simple_bram_vacc0_1 Latency = 2 dout0_1
a3 In4 Out4 d Z^-1 =q1
Latency pol1_in4 pol1_out4 in03 Latency = 2 Latency = 1
X >> 2 addr
pipeline16 -2 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
sim_a z
a4 In5 Out5 d Z^-1 =q1 pol1_in5 pol1_out5 in04 out02 -2 -5 -2 d Z^-2 q c Z^-5power d Z^-1 q -1 d Z^-1 q din valid d Z^-2 q we
Latency X >> 2 z z z z Latency =1 Latency =2
-2 Latency = 1 simple_bram_vacc0_2 Latency = 2 dout0_2
pipeline15 z Latency = 2 Latency = 1
a5 In6 Out6 d Z^-1 =q1
Latency pol1_in6 pol1_out6 in05 addr
X >> 2 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
pipeline14 -2 out03 -2 -5 -2 d Z^-2 q c Z^-5power d Z^-1 q -1 d Z^-1 q din valid d Z^-2 q we
z z z z z Latency =1 Latency =2
a6 In7 Out7 d Z^-1 =q1 pol1_in7 pol1_out7 in06 Latency = 1
Latency X >> 2 Latency = 2 Latency = 1 simple_bram_vacc0_3 Latency = 2 dout0_3
pipeline13 -2 addr
z
a7 In8 Out8 d Z^-1 =q1 pol1_in8 pol1_out8 in07 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
Latency X >> 2 -2 -5 -2 -1 d Z^-1 =q1 d Z^-2 =q2
out04 z z z d Z^-2 q c Z^-5power d Z^-1 q z Latency din valid Latency we
pipeline12 -2
z Latency = 1 simple_bram_vacc0_4 Latency = 2 dout0_4
a8 In9 Out9 d Z^-1 =q1 pol1_in9 pol1_out9 in08 Latency = 2 Latency = 1
Latency X >> 2 addr
pipeline77 -2 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
z
a9 In10 Out10 d Z^-1 =q1 pol1_in10 pol1_out10 in09 out05 -2 -5 -2 d Z^-2 q c Z^-5power d Z^-1 q -1 d Z^-1 =q1
Latency din valid d Z^-2 =q2
Latency we
Latency X >> 2 z z z z
-2 Latency = 1 simple_bram_vacc0_5 Latency = 2 dout0_5
pipeline76 z Latency = 2 Latency = 1
a10 In11 Out11 d Z^-1 =q1
Latency pol1_in11 pol1_out11 in010 addr
X >> 2 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
pipeline75 -2 out06 -2 -5 -2 d Z^-2 q c Z^-5power d Z^-1 q -1 d Z^-1 =q1 din valid d Z^-2 =q2 we
z z z z z Latency Latency
a11 In12 Out12 d Z^-1 =q1 pol1_in12 pol1_out12 in011 Latency = 1
Latency X >> 2 Latency = 2 Latency = 1 simple_bram_vacc0_6 Latency = 2 dout0_6
pipeline74 -2 addr
z
a12 In13 Out13 d Z^-1 =q1 pol1_in13 pol1_out13 in012 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
1 sim_sync Latency X >> 2 -2 -5 -2 -1 d Z^-1 =q1 d Z^-2 =q2
out07 z z z d Z^-2 q c Z^-5power d Z^-1 q z Latency din valid Latency we
pipeline73 -2
z Latency = 1 simple_bram_vacc0_7 Latency = 2 dout0_7
a13 In14 Out14 d Z^-1 =q1
Latency pol1_in14 pol1_out14 in013 Latency = 2 Latency = 1
X >> 2
pipeline72 -2

Block
z
a14 In15 Out15 d Z^-1 =q1
Latency pol1_in15 pol1_out15 in014 of
X >> 2

a15 In16 Out16


pipeline71
d Z^-1 =q1 pol1_in16 pol1_out16
z
-2
in015 Power Accumulators
RAMs
Latency X >> 2
pipeline69 pfb_fir_real0 fft_wideband_real0
sync_out conv_bus0 13 stages
Latency = 1 taps=4, add_latency=2
(18,18)
asiaa_adc5g0
Round (unbiased: +/- Inf)

FIR
Wrap

ADC FFT
Filter

Bandwidth: 1GHz
FFT channels: 4096
Freq. resolution: 244kHz
Dynamic Range: ∼ 86dB
Franco Curotto (DIE - U de Chile) Verilog 2019 3 / 37
¿Qué hacemos en Calán?

Aplicaciones:

I Mitigación de interferencia I Multi-beam Forming

Franco Curotto (DIE - U de Chile) Verilog 2019 4 / 37


Hardware Description Language (HDL)

I Lenguaje computacional para describir circuitos digitales


I Puede describir:
I Lógica combinacional
I Logica secuencial (sı́ncrona y ası́ncrona)
I Produce bitstreams para programar FPGAs, o netlists para diseñar
ASICs

Franco Curotto (DIE - U de Chile) Verilog 2019 5 / 37


Hardware Description Language (HDL)

I Lenguaje computacional para describir circuitos digitales


I Puede describir:
I Lógica combinacional
I Logica secuencial (sı́ncrona y ası́ncrona)
I Produce bitstreams para programar FPGAs, o netlists para diseñar
ASICs
C:
1 int main () { bin
2 printf ( " Hello , World ! " ) ; CPU
3 return 0;}

Verilog:
1 module neg ( input x , output y ) ; bitstream
2 assign y = ∼x ; FPGA
3 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 5 / 37


Hardware Description Language (HDL)
HDLs trabajan en la abstracción Register-transfer level

Te interesa: Generalmente no te preocupas de:


I El flujo de datos y los registros I Tecnologı́a del circuito (CMOS)
I Funcionalidad del circuito I Optimizaciones de lógica
I Interconecciones booleana
I Posicionamiento y enrutamiento
0
start
1 x0
y0
D Q
00 01 0
Q
0 0
0 x1 D Q y1
0 1 1
1 Q

11 10 clk
1
1 0
0
Franco Curotto (DIE - U de Chile) Verilog 2019 6 / 37
Lógica Combinacional - Operaciones Lógicas
I Módulo: unidad básica
I Los módulos se interconectan a través de sus inputs y outputs
I Los módulos pueden contener:
I variables (wires, regs)
I lógica combinacional y/o secuencial
I otros módulos

Franco Curotto (DIE - U de Chile) Verilog 2019 7 / 37


Lógica Combinacional - Operaciones Lógicas
I Módulo: unidad básica
I Los módulos se interconectan a través de sus inputs y outputs
I Los módulos pueden contener:
I variables (wires, regs)
I lógica combinacional y/o secuencial
I otros módulos
I Op. lógicas: NOT (∼), AND (&), OR (|), XOR (∧), XNOR (∼ ∧)

a e
b
c

a f
b y
c

a
b g
c

Franco Curotto (DIE - U de Chile) Verilog 2019 7 / 37


Lógica Combinacional - Operaciones Lógicas
I Módulo: unidad básica
I Los módulos se interconectan a través de sus inputs y outputs
I Los módulos pueden contener:
I variables (wires, regs)
I lógica combinacional y/o secuencial
I otros módulos
I Op. lógicas: NOT (∼), AND (&), OR (|), XOR (∧), XNOR (∼ ∧)

1 module comb ( input a ,b ,c ,


a e 2 output y ) ;
b
c 3
4 wire e ,f , g ;
a 5
f y
b 6 assign e = ∼a & ∼b & c;
c
7 assign f = ∼a & b & c;
8 assign g = a & b & c;
a 9
b g
c 10 assign y = e | f | g ;
11 endmodule
Franco Curotto (DIE - U de Chile) Verilog 2019 7 / 37
Lógica Combinacional - Operaciones Aritméticas
I Variables multi-bit: var[X:Y]
I X bit más significativo (MSB)
I Y bit menos significativo
(LSB)
I Operaciones matemáticas:
I Más utilizadas: +, -
I Menos utilizadas: *, /, %

Franco Curotto (DIE - U de Chile) Verilog 2019 8 / 37


Lógica Combinacional - Operaciones Aritméticas
I Variables multi-bit: var[X:Y] Sumador de 8 bits:
a
I X bit más significativo (MSB) 8
Cout
/ 1
I Y bit menos significativo
8 9 \
(LSB) b / + / 8
1 /
I Operaciones matemáticas: /
I Más utilizadas: +, - sum
I Menos utilizadas: *, /, % Cin

Franco Curotto (DIE - U de Chile) Verilog 2019 8 / 37


Lógica Combinacional - Operaciones Aritméticas
I Variables multi-bit: var[X:Y] Sumador de 8 bits:
a
I X bit más significativo (MSB) 8
Cout
/ 1
I Y bit menos significativo
8 9 \
(LSB) b / + / 8
1 /
I Operaciones matemáticas: /
I Más utilizadas: +, - sum
I Menos utilizadas: *, /, % Cin

1 module adder_8bit ( input [7:0] a , b ,


2 input Cin ,
3 output [7:0] sum ,
4 output Cout ) ;
5
6 wire [8:0] total_sum ;
7
8 assign total_sum = a + b + Cin ;
9 assign sum = total_sum [7:0];
10 assign Cout = total_sum [8];
11 endmodule
Franco Curotto (DIE - U de Chile) Verilog 2019 8 / 37
Lógica Combinacional - Bloque always

I Implementar tabla de verdad:


always + case
I always:
I Define un “bloque de
procesamiento”
I Modifica variables reg
I Lista de sensibilidad: define
cuándo se ‘activa’ el bloque

a b c y
0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 1
1 1 1 0
Franco Curotto (DIE - U de Chile) Verilog 2019 9 / 37
Lógica Combinacional - Bloque always
1 module truth_table ( input a ,b ,c ,
I Implementar tabla de verdad: 2 output y ) ;
always + case 3 reg [2:0] inputs_reg ;
4 reg y_reg ;
I always: 5
I Define un “bloque de 6 always @ (a ,b , c ) begin
7 inputs_reg = {a ,b , c };
procesamiento” 8
I Modifica variables reg 9 case ( inputs_reg )
I Lista de sensibilidad: define 10 3 ’ b000 : y_reg = 1;
cuándo se ‘activa’ el bloque 11 3 ’ b001 : y_reg = 0;
12 3 ’ b010 : y_reg = 0;
13 3 ’ b011 : y_reg = 0;
a b c y 14 3 ’ b100 : y_reg = 1;
0 0 0 1 15 3 ’ b101 : y_reg = 0;
0 0 1 0 16 3 ’ b110 : y_reg = 1;
0 1 0 0 17 3 ’ b111 : y_reg = 0;
0 1 1 0 18 default : y_reg = 0;
19 endcase
1 0 0 1
20 end
1 0 1 0 21
1 1 0 1 22 assign y = y_reg ;
1 1 1 0 23 endmodule
Franco Curotto (DIE - U de Chile) Verilog 2019 9 / 37
Lógica Combinacional - Bloque always
I {,}: operación de concatenación
I reg:
I Conserva su valor de una asignación a la siguiente
I Solo se puede modificar dentro de un bloque always
I No necesariamente representa un registro (memoria)!

Franco Curotto (DIE - U de Chile) Verilog 2019 10 / 37


Lógica Combinacional - Bloque always
I {,}: operación de concatenación
I reg:
I Conserva su valor de una asignación a la siguiente
I Solo se puede modificar dentro de un bloque always
I No necesariamente representa un registro (memoria)!
I Usar wire/assign para lógica combinacional simple
I Usar reg/always para lógica combinacional compleja y lógica
secuencial

Franco Curotto (DIE - U de Chile) Verilog 2019 10 / 37


Lógica Combinacional - Bloque always
I {,}: operación de concatenación
I reg:
I Conserva su valor de una asignación a la siguiente
I Solo se puede modificar dentro de un bloque always
I No necesariamente representa un registro (memoria)!
I Usar wire/assign para lógica combinacional simple
I Usar reg/always para lógica combinacional compleja y lógica
secuencial
Multiplexor con assign: Multiplexor con always:
1 module mux ( input d0 , d1 , s , 1 module mux ( input d0 , d1 , s ,
2 output y ) ; 2 output reg y ) ;
3 3
4 assign y = s ? d1 : d0 ; 4 always @ ( d0 , d1 , s ) begin
5 endmodule 5 if ( s ==1) : y = d1 ;
6 else : y = d0 ;
7 end
8 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 10 / 37


Lógica Secuencial - Flip Flop D
I Lógica secuencial: variable reg depende de sus valores pasados (i.e.
memoria)
I Comandos posedge/negedge:
I Circuito solo reacciona a los flancos de subida/bajada.
I Usado para implementar circuitos sı́ncronos.
I Flip flop D, con reset sı́ncrono (rst) y enable (en):

Franco Curotto (DIE - U de Chile) Verilog 2019 11 / 37


Lógica Secuencial - Flip Flop D
I Lógica secuencial: variable reg depende de sus valores pasados (i.e.
memoria)
I Comandos posedge/negedge:
I Circuito solo reacciona a los flancos de subida/bajada.
I Usado para implementar circuitos sı́ncronos.
I Flip flop D, con reset sı́ncrono (rst) y enable (en):

Franco Curotto (DIE - U de Chile) Verilog 2019 11 / 37


Lógica Secuencial - Flip Flop D
I Lógica secuencial: variable reg depende de sus valores pasados (i.e.
memoria)
I Comandos posedge/negedge:
I Circuito solo reacciona a los flancos de subida/bajada.
I Usado para implementar circuitos sı́ncronos.
I Flip flop D, con reset sı́ncrono (rst) y enable (en):

1 module FlipFlopD ( input D , rst , en , clk ,


2 output Q ) ;
3 wire D_wire ;
4 reg Q_reg ;
5
6 always @ ( posedge clk ) begin
7 if ( rst ) Q_reg <= 0;
8 else Q_reg <= D_wire ;
9 end
10
11 assign D_wire = en ? D : Q_reg ;
12 assign Q = Q_reg ;
13 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 11 / 37


Lógica Secuencial - Flip Flip v/s Latch
I Latches se generan cuando:
I No se usa posedge/negedge en el bloque always
I El valor de un reg no está definido para toda variable en la lista de
sensibilidad
I (Casi) nunca se debe usar implementaciones con latches:
I Su implementación es ineficiente
I Algunas FPGAs no pueden implementarlos
I Los circuitos sı́ncronos son más populares

Franco Curotto (DIE - U de Chile) Verilog 2019 12 / 37


Lógica Secuencial - Flip Flip v/s Latch
I Latches se generan cuando:
I No se usa posedge/negedge en el bloque always
I El valor de un reg no está definido para toda variable en la lista de
sensibilidad
I (Casi) nunca se debe usar implementaciones con latches:
I Su implementación es ineficiente
I Algunas FPGAs no pueden implementarlos
I Los circuitos sı́ncronos son más populares

Flip flip D: Latch D:


1 module FlipFlopD ( input D , clk , 1 module LatchD ( input D , clk ,
2 output reg Q ) ; 2 output reg Q ) ;
3 3
4 always @ ( posedge clk ) begin 4 always @ ( clk , D ) begin
5 Q <= D ; 5 if ( clk ) begin
6 end 6 Q <= D ;
7 endmodule 7 end
8 end
9 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 12 / 37


Lógica Secuencial - Blocking vs Non-blocking

I Blocking (=): cada asignación se evalúa secuencialmente (igual que en


un lenguaje de programación)
I Non-blocking (<=): cada asignación se evalúa en paralelo

1 always @ ( posedge clk ) 1 always @ ( posedge clk )


2 begin 2 begin
3 reg1 <= 1 ’ b1 ; 3 reg1 = 1 ’ b1 ;
4 reg2 <= reg1 ; 4 reg2 = reg1 ;
5 reg3 <= reg2 ; 5 reg3 = reg2 ;
6 end 6 end

¿Cuántos ciclos de reloj deben transcurrir para que para que reg3 tome el
valor 1 en ambos casos?

Franco Curotto (DIE - U de Chile) Verilog 2019 13 / 37


Lógica Secuencial - Blocking vs Non-blocking
Al programar lógica secuencial, casi siempre se usa non-blocking.

Franco Curotto (DIE - U de Chile) Verilog 2019 14 / 37


Lógica Secuencial - Blocking vs Non-blocking
Al programar lógica secuencial, casi siempre se usa non-blocking.
¿Qué circuito sintetizan ambos códigos?
1 module t ( input clk , A , 1 module t ( input clk , A ,
2 output reg B , C ) ; 2 output reg B , C ) ;
3 3
4 always @ ( posedge clk ) 4 always @ ( posedge clk )
5 begin 5 begin
6 B <= A ; 6 B = A;
7 C <= B ; 7 C = B;
8 end 8 end
9 9
10 endmodule 10 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 14 / 37


Lógica Secuencial - Blocking vs Non-blocking
Al programar lógica secuencial, casi siempre se usa non-blocking.
¿Qué circuito sintetizan ambos códigos?
1 module t ( input clk , A , 1 module t ( input clk , A ,
2 output reg B , C ) ; 2 output reg B , C ) ;
3 3
4 always @ ( posedge clk ) 4 always @ ( posedge clk )
5 begin 5 begin
6 B <= A ; 6 B = A;
7 C <= B ; 7 C = B;
8 end 8 end
9 9
10 endmodule 10 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 14 / 37


Lógica Secuencial - Blocking vs Non-blocking
Al programar lógica secuencial, casi siempre se usa non-blocking.
¿Qué circuito sintetizan ambos códigos?
1 module t ( input clk , A , 1 module t ( input clk , A ,
2 output reg B , C ) ; 2 output reg B , C ) ;
3 3
4 always @ ( posedge clk ) 4 always @ ( posedge clk )
5 begin 5 begin
6 B <= A ; 6 B = A;
7 C <= B ; 7 C = B;
8 end 8 end
9 9
10 endmodule 10 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 14 / 37


Lógica Secuencial - Flip Flop T y Flip Flop JK

Flip Flop T Flip Flop JK


I Inputs: T (toggle), clk I Inputs: J, K, clk
I Outputs: Q, Qneg (∼ Q) I Outputs: Q, Qneg (∼ Q)

J Q
T Q

Q
K Q

T Qn+1 J K Qn+1
0 Qn 0 0 Qn
1 ∼ Qn 0 1 0
1 0 1
1 1 ∼ Qn

Franco Curotto (DIE - U de Chile) Verilog 2019 15 / 37


Lógica Secuencial - Flip Flop T y Flip Flop JK

Flip Flop T Flip Flop JK


I Inputs: T (toggle), clk I Inputs: J, K, clk
I Outputs: Q, Qneg (∼ Q) I Outputs: Q, Qneg (∼ Q)
1 module FFT ( input T , clk , 1 module FFJK ( input J , K , clk ,
2 output reg Q , 2 output reg Q
3 output Qneg ) ;
3 output Q_neg ) ;
4
4
5 always @ ( posedge clk )
5 always @ ( posedge clk ) 6 begin
6 begin 7 case ({ J , K })
7 if ( T ) Q <= ∼Q ; 8 2 ’ b01 : Q <= 0;
8 end 9 2 ’ b10 : Q <= 1;
9
10 2 ’ b11 : Q <= ∼Q ;
11 default : Q <= Q ;
10 assign Q_neg = ∼Q ; 12 endcase
11 endmodule 13 end
14
15 assign Qneg = ∼Q ;
16 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 16 / 37


Lógica Secuencial - Máquina de Estados

Implementar la siguente máquina de estados:

0
start
1
00 01
0 0
0
0 1
1

11 10
1
1 0
0

Franco Curotto (DIE - U de Chile) Verilog 2019 17 / 37


Lógica Secuencial - Máquina de Estados
Implementar la siguiente máquina de estados:
1 module moore ( input x , rst , clk ,
2 output y ) ;
3 reg [1:0] state ;
4
5 always @ ( posedge clk , posedge rst ) begin
6 if ( rst ) state <= 2 ’ b00 ;
7 else begin
8 case ( state )
9 2 ’ b00 : if ( x ) state = 2 ’ b01 ;
10 else state = 2 ’ b00 ;
11 2 ’ b01 : if ( x ) state = 2 ’ b10 ;
12 else state = 2 ’ b00 ;
13 2 ’ b10 : if ( x ) state = 2 ’ b10 ;
14 else state = 2 ’ b11 ;
15 2 ’ b11 : if ( x ) state = 2 ’ b01 ;
16 else state = 2 ’ b00 ;
17 endcase
18 end
19 end
20
21 assign y = ( state == 2 ’ b11 ) ;
22 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 18 / 37


Instanciación de Módulos

I Forma de usar módulos creados dentro de otros módulos


I Se deben conectar las entradas y salidas del módulo hijo a variables
del módulo padre (wire, input, output).
I Dos métodos para especificar las entradas/salidas: por orden, y por
nombre

Franco Curotto (DIE - U de Chile) Verilog 2019 19 / 37


Instanciación de Módulos

I Forma de usar módulos creados dentro de otros módulos


I Se deben conectar las entradas y salidas del módulo hijo a variables
del módulo padre (wire, input, output).
I Dos métodos para especificar las entradas/salidas: por orden, y por
nombre

Implementar sumador de 16-bits usando sumadores de 8-bits:


I Tenemos:
1 module adder_8bit ( input [7:0] a , b , input Cin ,
2 output [7:0] sum , output Cout ) ;

I Debemos crear:
1 module adder_16bit ( input [15:0] a , b , input Cin ,
2 output [15:0] sum , output Cout ) ;

Franco Curotto (DIE - U de Chile) Verilog 2019 19 / 37


Instanciación de Módulos

Implementar sumador de 16-bits usando sumadores de 8-bits:

Diagrama:
adder 8bits concat
a[7:0] a 8 )
sum / 16
b[7:0] b / sum
Cout
Cin Cin

carry wire

adder 8bits
a[15:8] a 8
sum /
b[15:8] b
Cout / Cout
Cin 1

Franco Curotto (DIE - U de Chile) Verilog 2019 20 / 37


Instanciación de Módulos
Implementar sumador de 16-bits usando sumadores de 8-bits:
1 module adder_16bits ( input [15:0] a , b , input Cin ,
2 output [15:0] sum , output Cout ) ;
3
4 wire [7:0] a_lsb , b_lsb , a_usb , b_usb ;
5 wire [7:0] sum_lsb , sum_usb ;
6 wire carry_wire ;
7
8 assign a_lsb = a [7:0];
9 assign a_usb = a [15:8];
10 assign b_lsb = b [7:0];
11 assign b_usb = b [15:8];
12
13 // instanciacion por orden
14 adder_8bits lsb_adder ( a_lsb , b_lsb , Cin , sum_lsb , carry_wire ) ;
15 // instanciacion por nombre
16 adder_8bits usb_adder (. a ( a_usb ) , . b ( b_usb ) , . Cin ( carry_wire ) ,
17 . sum ( sum_usb ) , . Cout ( Cout ) ) ;
18
19 assign sum = { sum_usb , sum_lsb };
20 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 21 / 37


Diseño Structural vs Behavioral

I Behavioral Design: define funcionalidad del módulo


I Structural Design: define interconexión entre módulos
Regla general: Usar diseño behavioral para los módulos principales, y
structural para módulos de alto nivel.

Franco Curotto (DIE - U de Chile) Verilog 2019 22 / 37


Operadores

Prioridad Operación Significado


1 ∼ NOT
2 ∗, /, % mult, div, mod
3 +, − add, sub
4 <<, >> logical shift
5 <<<, >>> arithmetic shift
6 <, <=, >, >= relative comparison
7 ==, ! = equality comparison
8 &, ∼ & AND, NAND
9 ˆ, ∼ˆ XOR, XNOR
10 |, ∼ | OR, NOR
11 ?: conditional

Franco Curotto (DIE - U de Chile) Verilog 2019 23 / 37


Representación Numérica
Número Se almacena como
6’b10 00 0010
6’d10 00 1010
6’o10 00 1000
6’h10 01 0000
6’d60 11 1100
4’d60 1100
10’d60 00 0011 1100
’d60 0000 0000 0000 0000 0000 0000 0011 11 00
60 0000 0000 0000 0000 0000 0000 0011 11 00
8’d1 0000 0001
-8’d1 1111 1111
I Sintaxis <tamaño> ’ <base> <número>
I Bases: b: binario, d: decimal, o: octal, h: hexadecimal
I Tamaño por defecto: 32 bits
I Números negativos en complemento-2
Franco Curotto (DIE - U de Chile) Verilog 2019 24 / 37
Programación Gráfica vs Textual
Programación gráfica:

Franco Curotto (DIE - U de Chile) Verilog 2019 25 / 37


Programación Gráfica vs Textual
Programación gráfica:

Ventajas:
I Menor barrera de entrada
I Fácil de visualizar flujo de datos
I Rápido para diseños simples

Franco Curotto (DIE - U de Chile) Verilog 2019 25 / 37


Programación Gráfica vs Textual
Programación gráfica:

Ventajas: Desventajas
I Menor barrera de entrada I Tedioso de programar para
I Fácil de visualizar flujo de datos diseños grandes
I Rápido para diseños simples I Requiere más tiempo de
compilación/sı́ntesis
I Dificil de parametrizar
I Menos portable
Franco Curotto (DIE - U de Chile) Verilog 2019 25 / 37
Programación Gráfica vs Textual

Programación gráfica:

in_reg d Z^-2 q [a:b] [cnt_rst] in_reg d Z^-2 q [a:b] [filter_on] 60-120MHz

cnt_rst Latency = 2 filter_on Latency = 2


System 1input:uf32.0 = 32 bits 1input:uf32.0 = 32 bits
Generator
in_reg d Z^-2 q reinterpret [filter_gain]
MSSGE in_reg d Z^-2 q [acc_len]
ROACH Latency = 2 FDATool
filter_gain
acc_len Latency = 2
1input:uf32.0 = 32 bits
XSG_core_config 1input:uf32.0 = 32 bits
in_reg d Z^-2 q [filter_acc] in_reg d Z^-2 q [a:b] [channel]
sync_out d Z^-2 q [sync_gen]
filter_acc Latency = 2 channel Latency = 2
sync_gen Latency = 2
1input:uf32.0 = 32 bits 1input:uf32.0 = 32 bits
sim_sync_period=16384

[sync_gen] d Z^-1 q sync_in


adc0_s0 d Z^-1 =q1
Latency real1
Latency = 1 0 imag1 [acc_len] acc_len
-2 -2 -5 -2 d Z^-2 q -5 d Z^-1 q sync new_acc d Z^-1 q d Z^-2 q rst
z z z z z
en ++
1 adc0_sync_sim adc0_s1 d Z^-1 q real2 [cnt_rst] addr
rst
sync_out d Z^-1 q sync sync_out -2 Latency = 2 Latency = 1 Latency = 1 Latency = 2
Latency = 1 0 imag2 z sel d Z^-1 q d Z^-2 q reinterpret
xk_re reinterpret cast re acc_cntrl0 new_acc dout data_in data_out
adc0_s2 d Z^-1 q real3 Latency = 1 -1
z xn_re -2 c d0 -2 -5 -2 d Z^-2 q c Z^-5 power d Z^-1 q -1 Latency
d Z^-1 =q1 din valid Latency
d Z^-2 =q2 we
Latency = 1 0 imag3 z z z z z
xk_im reinterpret cast im
adc0_s3 d Z^-1 q real4 Latency = 2 Latency = 1 Latency = 1 simple_bram_vacc0_0 Latency = 2 dout0_0
0 d1
Latency = 1 0 imag4 xn_index
0 xn_im
adc0_s4 d Z^-1 q real5 -2
0 imag5
xk_index a z
Latency = 1
1 adc0_data_valid_sim d 2047 b a>b
adc0_s5 d Z^-1 q real6 [cnt_rst] rst z-1 q start rfd
0 imag6
re d Z^-1 q pol1_in1 pol1_out1
en
Latency = 1 dout c
im Latency = 1
adc0_s6 d Z^-1 q real7 reset_reg busy
Latency = 1 0 imag7 c_to_ri3
1 fwd_inv dv
adc0_s7 d Z^-1 q real8 8_7 r/i
Latency = 1 0 imag8
pfb_fir_real edone
adc0_sync
dec_fir taps=4, add_latency=1 0 fwd_inv_we
done
1 adc1_sync_sim 104 taps
adc0_outofrange
8_7 r/i FFT

adc0_data_valid
[sync_gen] d Z^-1 q sync_in
adc1_s0 d Z^-1 =q1
Latency real1 [acc_len] acc_len
-2 -2 -5 -2 d Z^-2 q -5 d Z^-1 q sync new_acc d Z^-1 q d Z^-2 q rst
z z z z z
Latency = 1 0 imag1 [cnt_rst] rst en ++ addr
adc1_s1 d Z^-1 q real2 -2 sel Latency = 2 Latency = 1 Latency = 1 Latency = 2
z acc_cntrl1 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
sync_out d Z^-1 q sync sync_out xk_re reinterpret cast re
1 adc1_data_valid_sim Latency = 1 0 imag2 -1 xn_re
z -2 c d0 -2 -5 -2 d Z^-2 q c Z^-5 power d Z^-1 q -1 Latency
d Z^-1 =q1 din valid Latency
d Z^-2 =q2 we
adc1_s2 d Z^-1 q real3 Latency = 1 z z z z z
xk_im reinterpret cast im
Latency = 1 0 imag3 Latency = 2 Latency = 1 Latency = 1 simple_bram_vacc1_0 Latency = 2 dout1_0
0 d1
adc1_s3 d Z^-1 q real4 xn_index
0 xn_im
Latency = 1 0 imag4 -2
adc1_s4 d Z^-1 q real5
xk_index a z
d 2047 b a>b
Latency = 1 0 imag5 [cnt_rst] rst z-1 q start rfd
adc1_s5 d Z^-1 q real6 en
sim_adc0_data_in
0 imag6
re d Z^-1 q pol1_in1 pol1_out1
busy
Latency = 1 dout c reset_reg1
im Latency = 1
adc1_s6 d Z^-1 q real7
1 fwd_inv
0 imag7 c_to_ri4 dv
Latency = 1
adc1_s7 d Z^-1 q real8 8_7 r/i
edone
Latency = 1 0 imag8
pfb_fir_real1 0 fwd_inv_we
adc1_sync
taps=4, add_latency=1 done
dec_fir1
104 taps FFT1
adc1_outofrange
sim_adc1_data_in 8_7 r/i

adc1_data_valid
Decimation PFB FIR Xilinx FFT [acc_len]

FIR Filter
adc083000x2 acc_len
-2 d Z^-2 q -5 d Z^-1 q sync new_acc d Z^-1 q d Z^-2 q rst
z z
en ++
[cnt_rst] addr
rst
Latency = 2 Latency = 1 Latency = 1 Latency = 2

ADC
acc_cntrl2 d Z^-1 q new_acc dout d Z^-2 q reinterpret data_in data_out
a
a Z^-2 a-b Latency
d Z^-2 q c Z^-5power d Z^-1 q -1 d Z^-1 =q1 din valid Latency
d Z^-2 =q2 we

Filter
ab b z
[weig0] b Latency = 2 Latency = 1 Latency = 1 simple_bram_vacc2_0 Latency = 2
18_17 * 18_17 ==> 18_17 dout2_0
18_17 * 64_35 ==> 18_17 Truncate, Wrap
Round (unbiased: Even Values), Wrap Latency=2
Latency=0

z
-5
z
-1 d Z^-1 q d Z^-2 q z
-5 d Z^-2 q ++
rst a
Latency = 1 Latency = 2 Latency = 2 weig_addr a-b

++
rst b

[filter_acc] acc_len ref_fft_addr


sync new_acc
[cnt_rst] rst
acc_cntrl3 [filter_on] on
-5
[filter_gain] a z
din Z^-2048 dout d Z^-2 q re
d Z^-1 q new_acc dout d Z^-2 q b a×b
re z
-1 d Z^-1 =q1
Latency din valid d Z^-2 =q2
Latency z
-5 we Latency = 2
Latency = 1 simple_bram_vacc3_r0 Latency = 2 weig_r0 c din
a dout [weig0]
[filter_on] 64_35, Signed
ab c -5 on delay
b [filter_gain] a z Round (unbiased: +/- Inf), Wrap
d Z^-1 q new_acc dout d Z^-2 q b a×b din Z^-2048 dout d Z^-2 q im delay_bram_prog0
cmult12
im z
-1 d Z^-1 =q1
Latency din valid d Z^-2 =q2
Latency z
-5 we Latency = 2
18_17 * 18_17 ==> 37_35
Round (unbiased: Even Values), Wrap Latency = 1 simple_bram_vacc3_i0 Latency = 2 weig_i0

Adaptive Filter
Latency=0 64_35, Signed ri_to_c5
c_to_ri Round (unbiased: +/- Inf), Wrap
37_35 r/i

Franco Curotto (DIE - U de Chile) Verilog 2019 26 / 37


Proceso de Compilación FPGA (Xilinx)

1. Sı́ntesis: Transforma código


HDL en netlists
2. Traducción: Combina netlists y
restricciones (I/O)
3. Mapeo: Transforma netlist en
recursos de la FPGA (CLB)
4. Place & Route: posiciona e
interconecta recursos
5. Análisis temporal: verifica que
circuito cumple restricciones de
tiempo
6. Generación de bitstream: para
programar FPGA

Franco Curotto (DIE - U de Chile) Verilog 2019 27 / 37


Archivo de Restricción

I Mapea pines (periféricos) de la FPGA con variables en Verilog


I Define velocidad del circuito (frecuencia de reloj)
I Opcionalmente se puede posicionar manualmente recursos de la
FPGA (floorplaning)

Franco Curotto (DIE - U de Chile) Verilog 2019 28 / 37


Archivo de Restricción

I Mapea pines (periféricos) de la FPGA con variables en Verilog


I Define velocidad del circuito (frecuencia de reloj)
I Opcionalmente se puede posicionar manualmente recursos de la
FPGA (floorplaning)

Mapeo para los botones de la Spartan-3E FPGA Starter Kit:


1 NET " BTN_EAST " LOC = " H13 " | IOSTANDARD = LVTTL | PULLDOWN ;
2 NET " BTN_NORTH " LOC = " V4 " | IOSTANDARD = LVTTL | PULLDOWN ;
3 NET " BTN_SOUTH " LOC = " K17 " | IOSTANDARD = LVTTL | PULLDOWN ;
4 NET " BTN_WEST " LOC = " D18 " | IOSTANDARD = LVTTL | PULLDOWN ;

Definición de periodo de reloj para la Spartan-3E FPGA Starter Kit:


1 // Define clock period for 50 MHz oscillator
2 NET " CLK_50MHZ " PERIOD = 20.0 ns HIGH 40 %;

Franco Curotto (DIE - U de Chile) Verilog 2019 28 / 37


Recursos

I Especificación IEEE del standard Verilog: http:


//staff.ustc.edu.cn/~songch/download/IEEE.1364-2005.pdf

I Tutorial Verilog en español: http://www.iuma.ulpgc.es/~nunez/


clases-FdC/verilog/VerilogTutorialv1.pdf

I Tutorial FPGA: https://www.nandland.com/articles/


fpga-101-fpgas-for-beginners.html
I Compiladores Gratis de Verilog:
I http://www.clifford.at/yosys/
I http://iverilog.icarus.com/
I https:
//www.tutorialspoint.com/compile_verilog_online.php

I GTKWave, visualizador de señales para simulaciones:


http://gtkwave.sourceforge.net/
Franco Curotto (DIE - U de Chile) Verilog 2019 29 / 37
Hardware Description Language:
Verilog

Franco Curotto

Departamento de Ingenierı́a Eléctrica


Facultad de Ciencias Fı́sicas y Matemáticas
Universidad de Chile

2019

Franco Curotto (DIE - U de Chile) Verilog 2019 30 / 37


Tópicos Avanzados - Parametrización
Puedes crear módulos con parámetros que se pueden cambiar al momento
de la instanciación.

Sumador genérico de N bits:


1 module adder_Nbits #( parameter N = 8)
2 ( input [N -1:0] a , input [N -1] b , input Cin ,
3 output [N -1:0] sum , output Cout ) ;
4
5 wire [ N :0] total_sum ;
6
7 assign total_sum = a + b + Cin ;
8 assign sum = total_sum [N -1:0];
9 assign Cout = total_sum [ N ];
10 endmodule

Franco Curotto (DIE - U de Chile) Verilog 2019 31 / 37


Tópicos Avanzados - Parametrización
Puedes crear módulos con parámetros que se pueden cambiar al momento
de la instanciación.

Sumador genérico de N bits:


1 module adder_Nbits #( parameter N = 8)
2 ( input [N -1:0] a , input [N -1] b , input Cin ,
3 output [N -1:0] sum , output Cout ) ;
4
5 wire [ N :0] total_sum ;
6
7 assign total_sum = a + b + Cin ;
8 assign sum = total_sum [N -1:0];
9 assign Cout = total_sum [ N ];
10 endmodule

Para crear un sumador de 8 bits:


1 addr_Nbits #(8) adder_8bits (a , b , Cin , sum , Cout ) ;

Franco Curotto (DIE - U de Chile) Verilog 2019 31 / 37


Tópicos Avanzados - Arreglos
I Arreglos son conjuntos de reg/wire agrupados en una variable que
puede ser indexada.
I Útil para definir grandes grupos de memoria (RAM, ROM, etc).
Módulo RAM de 256 palabras (dirección de 8 bits) de tamaño 16 bits.
1 module RAM256x16 ( input [7:0] i_addr ,
2 input [15:0] i_data ,
3 input i_clk , i_we , i_re ,
4 output reg [15:0] or_data ) ;
5
6 reg [15:0] mem [255:0];
7
8 always @ ( posedge i_clk ) begin
9 if ( i_we ) mem [ i_addr ] <= i_data ;
10 if ( i_re ) or_data = mem [ i_addr ];
11 end
12 endmodule
¿Cómo parametrizarı́a este módulo para que soporte un número arbitrario
de palabras y tamaños de palabras?
Franco Curotto (DIE - U de Chile) Verilog 2019 32 / 37
Tópicos Avanzados - Iteraciones
I HDLs permiten en uso de iteraciones (for/while)
I Iteraciones en HDLs son DISTINTAS a las iteraciones en software
I Se usan para declarar de manera compacta lógica repetitiva
Shift register de tamaño 4 usando ciclo for:
1 module ShiftRegister4 ( input x , clk ,
2 output y ) ;
3
4 reg [3:0] shift_regs ;
5
6 always @ ( posedge clk ) begin
7 shift_regs [0] <= x ;
8 for ( i =0; i <3; i = i +1) begin
9 shift_regs [ i +1] <= shift_regs [ i ];
10 end
11 end
12
13 assign y = shift_regs [3];
14 endmodule
Franco Curotto (DIE - U de Chile) Verilog 2019 33 / 37
Tópicos Avanzados - Testbenchs
Recordemos nuestro módulo detector de secuencia 110:
1 module moore ( input x , rst , clk ,
2 output y ) ;
3 reg [1:0] state ;
4
5 always @ ( posedge clk , posedge rst ) begin
6 if ( rst ) state <= 2 ’ b00 ;
7 else begin
8 case ( state )
9 2 ’ b00 : if ( x ) state = 2 ’ b01 ;
10 else state = 2 ’ b00 ;
11 2 ’ b01 : if ( x ) state = 2 ’ b10 ;
12 else state = 2 ’ b00 ;
13 2 ’ b10 : if ( x ) state = 2 ’ b10 ;
14 else state = 2 ’ b11 ;
15 2 ’ b11 : if ( x ) state = 2 ’ b01 ;
16 else state = 2 ’ b00 ;
17 endcase
18 end
19 end
20
21 assign y = ( state == 2 ’ b11 ) ;
22 endmodule
Franco Curotto (DIE - U de Chile) Verilog 2019 34 / 37
Tópicos Avanzados - Testbenchs
I Código Verilog usado para verificar el funcionamiento de un módulo
(no sintetizable)
I Variables se usan como señales de entrada y salida para el módulo
I Idealmente deben ser self-checking : el testbench mismo debe decir si
el módulo ésta o no está funcionando correctamente
1 ‘include " moore . v "
2
3 module moore_tb ;
4
5 // test variables
6 reg x = 1 ’ b0 ;
7 reg rst = 1 ’ b0 ;
8 reg clk = 1 ’ b0 ;
9 wire y ;
10
11 moore DUT (. x ( x ) , . rst ( rst ) , . clk ( clk ) , . y ( y ) ) ; // device
under test
12 always #10 clk <= ! clk ; // clock period : 10 time units
Franco Curotto (DIE - U de Chile) Verilog 2019 35 / 37
Tópicos Avanzados - Testbenchs
1 // main test routine
2 initial begin
3 // reset circuit
4 #1 rst = 1 ’ b1 ; // # X = delay X time units
5 #1 rst = 1 ’ b0 ;
6 // generate sequence signal to detect
7 @ ( posedge clk ) ; // wait for the next clock posedge
8 #1 x = 1 ’ b1 ; // current sequence : 1
9 @ ( posedge clk ) ; // wait for the next clock posedge
10 #1 x = 1 ’ b1 ; // current sequence : 11
11 @ ( posedge clk ) ; // wait for the next clock posedge
12 #1 x = 1 ’ b0 ; // current sequence : 110
13 @ ( posedge clk ) ; // wait for the next clock posedge
14 #10; // delay 10 time units for visualization
15 // check sequence detection
16 if ( y ==1) $display ( " Sequence 110 detected ! State machine working . " ) ;
17 else $display ( " Sequence 110 not detected :(. Check i mplement ation . " ) ;
18 $finish () ;
19 end
20 // generate file for simulation
21 initial begin
22 $dumpfile ( " dump . vcd " ) ;
23 $dumpvars (0) ;
24 end
25 endmodule
Franco Curotto (DIE - U de Chile) Verilog 2019 36 / 37
Tópicos Avanzados - Simulación

I Simulación realizada con Icarus Verilog y GTKWave


I Instrucciones de uso: link

Franco Curotto (DIE - U de Chile) Verilog 2019 37 / 37

You might also like