Você está na página 1de 67

Linguagem de Descrição de

Hardware - VERILOG

PROF. MARCO AURÉLIO BENEDETTI RODRIGUES

PROF. EM ESTÁGIO DOCÊNCIA ÉRICO CAVALCANTE


A linguagem Verilog

 A linguagem Verilog foi introduzida em 1985 pela Gateway Design


Automation.
 A Gateway foi comprada pela empresa Cadence Design Systems, em
1989, que tornou a linguagem de domínio público em maio de 1990
com a formação da Open Verilog International (OVI).
 Hoje o Verilog é um padrão IEEE, já tendo duas extensões ou
modificações: Verilog-95 (padrão IEEE 1364-1995), Verilog 2001 (IEEE
1364-2001) e Verilog 2005 (IEEE 1364-2005).
 O Verilog tem uma grande semelhança com a linguagem de
programação C.
A linguagem Verilog

 Projeto, implementação e verificação de chips de lógica


digital. Pode ser usada na verificação de circuitos
analógicos ou mistos
 Linguagem similar à linguagem C
 Possui todos os operadores de C
 Uso de begin e end em vez de { e }
A linguagem Verilog

 Construtores de escopo hierárquicos


 Definição de módulos

 Definição de funções

 Definição de tarefas

 Blocos de instruções identificados (begin/end)

 Utilização direta de strings e operadores aritméticos

 // texto com comentario ou /* texto com


comentario*/
Palavras reservadas em VERILOG

always edge function nmos real strong0 unsigned


and else highz0 nor realtime strong1 vectored
assign end highz1 not reg supply0 wait
attibute endattribute if notif0 release supply1 wand
begin endcase ifnone notif1 repeat table weak0
buf endfunction initial or rnmos task weak1
bufif0 endmodule inout output rpmos time while
bufif1 endprimitive input parameter rtran tran wire
case endspecify integer pmos rtranif0 tranif0 wor
casex endtable join posedge rtranif1 tranif1 xnor
casez endtask large primitive scalared tri xor
cmos event macromodul pull0 signed tri0
deassign for medium pull1 small tri1
default force module pulldown specify triand
defparam forever nand pullup specparam trior
disable fork negedge rcmos strength trireg
Niveis Lógicos em Verilog

 Lógica de 4 estados
 0 zero, baixo ou falso
 1 um, alto ou verdadeiro
 z ou Z alta impedancia (flutuante ou 3-state)
 x ou X desconhecido ou nao inicializado
Niveis Lógicos em Verilog

 Níveis de forcas lógicas


Verilog – Funções do sistema

 $display Print to screen a line followed by an


automatic newline
 $write Write to screen a line without the newline
 $swrite Print to variable a line without the newline
 $sscanf Read from variable a format-specified string
 $fopen Open a handle to a file (read or write)
 $fdisplay Write to file a line followed by an automatic
newline
 $fwrite Write to file a line without the newline
 $fscanf Read from file a format-specified string
Verilog – Funções do sistema

 $fclose Close and release an open file-handle


 $readmemh Read hex file content into a memory array
 $readmemb Read binary file content into a memory array
 $monitor Print out all the listed variables when any change
value
 $time Value of current simulation time
 $dumpfile Declare the VCD (Value Change Dump) format
output filename
 $dumpvars Turn on and dump the variables
 $dumpports Turn on and dump the variables in Extended-VCD
format
 $random Return a random value
Definições em VERILOG

Tipos em Verilog
Constantes
Ex.: parameter word = 23, count=50;
 Entradas e saidas
input a, b, sel
input [word-1 : 0] addr;
output [7:0] result;
inout [15:0] data;
 Ligações e Barramentos
wire a, b, c;
reg [0:8] res; //Armazena o valor em memoria
Comandos e expressões

o Operadores aritméticos e lógicos (utilizados diretamente)

Adição e subtração: + , -
Multiplicação, divisão e resto: * , /,| %
Operadores a nível de bit: ~ , & , | , ^
Operadores Lógicos: ! , && , ||
Rotação : << , >>

o Outros operadores

Seleção: sel ? m : n // se sel então m senão n


Concatena: { m , n } // concatena m a n
Replicar : { n { m } } // replica m n vezes
Comandos Lógicos para programação

 Comando if
 if ( expr ) cmd else cmd

 Comando Case
Case identificador
match : cmd
default : cmd
endcase
Comandos Lógicos para programação

 Comando repeat
 repeat ( número ) cmd

 Comando while
 while ( expr ) cmd

 Comando for
 for ( assignment , expr , assignment ) cmd
Verilog

Módulo – Definição Geral Exemplo:

module <nome do módulo> module meu_and


( declaração das portas ); (output reg C,

declaração de variáveis; input A, B);
… always @ (A, B) begin
descrição do comportamento C = A & B; // & operador AND
endmodule
end
endmodule
Verilog

Comentários em Verilog
// comentário de uma linha só
/* outra forma de comentário de uma linha */
/* inicio de comentário com múltiplas linhas
todo text é ignorado
termina com a linha abaixo*/
Números
decimal, hexadecimal, octal, binario
Decimal sem sinal
Decimal com sinal
Cadeias de caracteres
"Delimite usando aspas numa mesma linha"
limitados a 1024 caracteres
Verilog

Modelos de Descrição

• Estrutural: descreve um circuito lógico através da interligação dos componentes


que os compõe.

• Fluxo de dados: descreve um circuito através das funções booleanas que os


compõe.
• Comportamental: descreve o circuito através do comportamento do mesmo, na
forma de um algoritmo.

• RTL (Register Transfer Level): descreve o circuito através do que acontece a cada
transição ativa do sinal de relogio
Verilog

Exemplo :

module soma_fluxo_de_dados
(output S, Cout,
input A, B, Cin);
assign S = A ^ B ^ Cin;
assign Cout = (A & B) | (A & Cin) | (B & Cin);
endmodule
VERILOG: Exemplo: Modelo
Comportamental do Multiplexador

Tabela Verdade do Multiplexador


sel out
Descrição Verilog:
0 a
module comportamental_mux
1 b (output reg out,
input a, b, sel);
Símbolo do Mux:
always @(a,b, sel) begin
if (sel == 0)
out = a;
else
out = b;
end
endmodule
Exemplos

 Controle de tempo
 # delay // atrasa delay unidades de tempo
 wait ( expr )

// 1000 vezes um clock de 50 ns


begin
Clk = 0;
# 1000 forever #25 clk := - clk;
End module m555 (output reg clock);
initial
#5 clock =1;
always
#50 clock = ~ clock;
endmodule
Exemplos

 Multiplexador
// um multiplezador de 32 bit 2-to-1 MUX
wire [31:0] mux_out;
assign mux_out = sel ? a : b; //valor inicial

//Portas AND-OR-INVERT
module AOI (input A, B, C, D, output F) ;
assign F = ~ ( (A & B) | (C & D) ) ; // Associação
End module wire out ;
assign out = sel ? a : b ;
Exemplos

// Usando um procedimento
reg out;
always @(a or b or sel) // Usando if/else
begin
reg out;
case ( sel )
always @ ( a or b or sel )
1'b0: out = b ; if ( sel )
1'b1: out = a ; out = a ;
else
endcase
out = b ;
end
Exemplos

module binaryToESeg
(output reg eSeg,
input A, B, C, D);
always @(A, B, C, D)
begin
eSeg = 1;
if (~A & D) if (~A & B & ~C)
eSeg = 0; eSeg = 0;
if (~B & ~C & D)
eSeg = 0;
end
endmodule
Flip Flops

module toplevel(clock, reset);


input clock;
input reset;
reg flop1;
reg flop2;
always @ (posedge reset or posedge clock)
if (reset)
else
begin begin
flop1 <= 0; flop1 <= flop2;
flop2 <= 1; flop2 <= flop1;
end end
endmodule
Exemplo DFF

 module synDFFwithSetReset
(output reg q, input d, reset, set, clock);

always @(posedge clock, negedge reset, posedge set) begin


if (~reset)
q<=0;
else if (set)
q <= 1;
else q <= d;
end
endmodule
Exemplos

module addsub
(
input [7:0] dataa,
input [7:0] datab,
input add_sub, // if this is 1, add; else subtract
input clk,
output reg [8:0] result begin
); if (add_sub)
result <= dataa + datab;
always @ (posedge clk) else
result <= dataa - datab;
end
End module
Exemplos Contador

module counter
always @(posedge clk or posedge
( reset)
clk, begin
reset, if (reset)
result, result = 0;
ena
); else if (ena)
input clk; result = result + 1;
input reset; end
endmodule
input ena;
output [7:0] result;
reg [7:0] result;
Exemplo DFF

module dffeveri (q, d, clk, ena, rsn, if (~prn)


prn); begin
if (rsn) q = 1'b1;
// port declaration else q = 1'bx;
input d, clk, ena, rsn, prn;
end
output q; reg q;

//asynchronous active-low reset


always @ (posedge clk or negedge rsn
or negedge prn) else if (~rsn) q = 1'b0;

begin //enable
//asynchronous active-low preset else if (ena) q = d;
end endmodule
Exemplo

 CASE 3'b100: f = 1'b1;


module synCase 3'bl0l: f = 1'b0;
(output reg f, input a, b, c);
3'b110: f = 1'b0;
always @(*)
3'b111: f = 1'b1;
case ({a, b, c})
End case
3'b000: f = 1'b0;
End module
3'b00l: f = 1'b1;
3'b0l0: f = 1'b1;
3'b011: f = 1'b1;
Tri-States

module synTriState(output reg bus,


input in, driveEnable);
always @(*)
if (driveEnable)
bus = in;
else bus = 1'bz;
endmodule
Barramentos
module mark1Case;
reg[15:0] signed m [0:8191];
//signed 8192 x 16 bit memory
reg [12:0] signed pc; 3'b0l0 : acc <= -m [ir [12:0]];
// signed 13 bit program counter 3'b011: m [ir [12:0]] <= acc;
reg [12:0] signed acc;
3'b100,
// signed 13 bit accumulator
reg [15:0] ir;
3'bl0l : acc <= acc - m [ir [12:0]];
// 16 bit instruction register 3'bll0 : if(acc<0)pc<=pc + l;
reg ck; // a clock signal endcase
pc <= pc + 1;
always @(posedge ck)
end
begin
endmodule
case (ir [15:13])
3'b000 : pc <= m [ir [12:0]];
3'b001: pc <= pc + m [ir [12:0]];
Maquina de estados
module statem(clk, in, reset, out); always @(posedge clk or posedge reset)
input clk, in, reset; begin
output [3:0] out;
if (reset) state = zero;
reg [3:0] out;
else case (state)
reg [1:0] state;
zero: state = one;
parameter zero=0, one=1, two=2, three=3;
one: if (in) state = zero;
always @(state)
else state = two;
begin case (state)
zero: out = 4'b0000; two: state = three;
one: out = 4'b0001; three: state = zero;
two: out = 4'b0010; endcase
three: out = 4'b0100; end
default: out = 4'b0000; endmodule
end case
end
Maquina de estados

always @ (state)
begin
// 4-State Moore state machine case (state)
module moore_mac S0: data_out = 2'b01;
( S1: data_out = 2'b10;
S2:data_out = 2'b11;
input clk, data_in, reset,
output reg [1:0] data_out S3:data_out = 2'b00;
); default: data_out = 2'b00;
// Declare state register endcase
reg [1:0]state; end
// Declare states
parameter S0 = 0, S1 = 1, S2 = 2, S3 = 3;
// Output depends only on the state
Maquina de Estados
// Determine the next state S2: if (data_in)
always @ (posedge clk or posedge reset) state <= S3;
begin else
if (reset) state <= S1;
state <= S0; S3:if (data_in)
else state <= S2;
else
case (state)
state <= S3;
S0:state <= S1;
endcase
S1: if (data_in)
end
state <= S2;
else
state <= S1;
RAM

module ram
(
input [7:0] data,
input [5:0] read_addr, write_addr, always @ (posedge clk)
input we, clk, begin
output reg [7:0] q // Write
); if (we)
ram[write_addr] <= data;
// Declare the RAM variable
else
reg [7:0] ram[63:0]; q <= ram[read_addr];
end
endmodule
Memória RAM

module mem_ram_sync(
clk,
rst,
read_rq,
write_rq,
rw_address,
write_data,
read_data
);
input clk;
input rst;
input read_rq;
input write_rq;
input[5:0] rw_address;
input[7:0] write_data;
output[7:0] read_data;
reg[7:0] read_data;
integer out, i;
Memória RAM
// Declare mmory 64x8 bits = 512 bits or 64 bytes
reg [7:0] memory_ram_d [63:0];
reg [7:0] memory_ram_q [63:0];

// Use positive edge of clock to read the memory


// Implement cyclic shift right
always @(posedge clk or
negedge rst)
begin
if (!rst)
begin
for (i=0;i<64; i=i+1)
memory_ram_q[i] <= 0;
end
else
begin
for (i=0;i<64; i=i+1)
memory_ram_q[i] <= memory_ram_d[i];
end
end
Memória RAM

always @(*)
begin
for (i=0;i<64; i=i+1)
memory_ram_d[i] = memory_ram_q[i];
if (write_rq && !read_rq)
memory_ram_d[rw_address] = write_data;
if (!write_rq && read_rq)
read_data = memory_ram_q[rw_address];
end
endmodule
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
LCD
Exercício

 Jogo da Velocidade
 Fazer um Código em Verilog para:
 Identificar o acionamento do botão para ativar a
contagem de 10 segundos para acionamento das chaves
 Identificar o acionamento de 5 chaves e ligar cinco LEDs,
identificando qual a ordem de acionamento das chaves.
 Identificar o primeiro acionamento (primeira chave a ser
pressionada), acender o LED correspondente. Identificar
a segunda chave acionada, esperar um segundo, acionar
o LED correspondente, e assim sucessivamente até o
último LED.

Você também pode gostar