DLP29006-Engtelecom(2019-2) - Prof. Marcos Moecke
MURAL DE AVISOS E OPORTUNIDADES DA ÁREA DE TELECOMUNICAÇÕES
Registro on-line das aulas
Unidade 1 - Introdução a disciplina
- 3 AULAS
Unidade 2 - Introdução ao VHDL e ambienta EDA - QUARTUS
- 3 AULAS
Unidade 2 - Introdução ao VHDL e ambienta EDA - QUARTUS |
---|
library library_name;
use library_name.package)name.all;
entity entity_name is
[generic (
cons_name1: const_type const_value;
cons_name2: const_type const_value;
...
cons_nameN: const_type const_value);]
[port (
signal_name1: mode signal_type;
signal_name2: mode signal_type;
...
signal_nameN: mode signal_type);]
[declarative_part]
[begin
statement_part]
end [entity] [entity_name];
architecture arch_name of entity_name is
[declarative_part]
begin
statement_part
end [architecture] [arch_name];
library std;
use std.standard.all;
entity nand_gate is
port (a, b: in bit; x: out bit);
end entity;
architecture nome_arch of nand_gate is
begin
x <= a nand b;
end architecture;
-- Declaração das bibliotecas e pacotes
LIBRARY ieee;
USE ieee.std_logic_1164.all;
-- Especificação de todas as entradas e saídas do circuito
ENTITY flip_flop IS
PORT (d, clk, rst: IN STD_LOGIC;
q: OUT STD_LOGIC);
END;
-- Descrição de como o circuito deve funcionar
ARCHITECTURE flip_flop OF flip_flop IS
BEGIN
PROCESS (clk, rst)
BEGIN
IF (rst='1') THEN
q <= '0';
ELSIF (clk'EVENT AND clk='1') THEN
q <= d;
END IF;
END PROCESS;
END;
![]()
![]()
![]()
ls /opt/altera/13.0sp1/quartus/libraries/vhdl/std
ls /opt/altera/13.0sp1/quartus/libraries/vhdl/ieee
ls /opt/altera/13.0sp1/quartus/libraries/vhdl/mentor/arithmetic (Mentor Graphics) ls /opt/altera/13.0sp1/quartus/libraries/vhdl/synopsys/ieee (Synopsys)
ls /opt/altera/16.0/quartus/libraries/vhdl/ieee/2008
![]()
Video motivational para apreender FPGA, VHDL Microsoft's Bing* Intelligent Search with Intel® FPGAs
![]() ![]() Note que na simulação funcional a mudança da saída Q ocorre no instante em que ocorre a borda de subida do clock ou no momento do reset. No entanto, no caso da simulação com timing, existe um atraso de ~6ns nestas mudanças. IMPORTANTE: Na prática normalmente não é necessário fazer a simulação temporal, pois através do Time Quest Report é possível verificar se o circuito atende as restrições de tempo.
create_clock -name CLK50MHz -period 50MHz [get_ports {*}]
/opt/altera/13.0sp1/modelsim_ae/bin/vsim
cd /home/nome_usuario/nome_pasta/...
pwd ls
vlib work vcom -work work n_flip_flop.vhd
vsim work.n_flip_flop
wave create -pattern none -portmode in -language vhdl -range N 1 /n_flip_flop/d wave create -pattern none -portmode in -language vhdl /n_flip_flop/clk wave create -pattern none -portmode in -language vhdl /n_flip_flop/rst wave create -pattern none -portmode out -language vhdl -range 1 N /n_flip_flop/q Será aberta uma janela [Wave] na qual irão ser mostrados as 3 portas de entrada da Entity e a porta de saída. Clique sobre o sinal da porta de saída e [Delete], pois esse sinal não será editado. Aproveite para arrastar com o mouse os sinais na janela Wave para ficarem na seguinte ordem: rst, clk, d.
Clique_direito sobre o sinal rst e selecione [Edit > Create/Modify Waveform] e escolha [Patterns = Constant], [Start Time = 0] [End Time = 1000] [Time Unit = ps] e clique em [Next], [Value = 0] e clique em [Finish]. Ou wave modify -driver freeze -pattern constant -value 0 -starttime 0ps -endtime 1000ps Edit:/n_flip_flop/rst Clique_direito sobre o sinal rst e selecione [Edit > Create/Modify Waveform] e escolha [Patterns = Constant], [Start Time = 20] [End Time = 30] [Time Unit = ps] e clique em [Next], [Value = 1] e clique em [Finish]. Ou wave modify -driver freeze -pattern constant -value 1 -starttime 20ps -endtime 30ps Edit:/n_flip_flop/rst
Clique_direito sobre o sinal clk e selecione [Edit > Create/Modify Waveform] e escolha [Patterns = Clock], [Start Time = 0] [End Time = 1000] [Time Unit = ps] e clique em [Next], [Initial Value = 1], [Clock Period = 100ps], [Duty Cycle = 50] e clique em [Finish]. Ou wave modify -driver freeze -pattern clock -initialvalue 1 -period 100ps -dutycycle 50 -starttime 0ps -endtime 1000ps Edit:/n_flip_flop/clk
Clique_direito sobre o sinal d e selecione [Edit > Create/Modify Waveform] e escolha [Patterns = Counter], [Start Time = 0] [End Time = 1000] [Time Unit = ps] e clique em [Next], [Start Value = 0000], [End Value = 1111], [Time Period = 120ps], [Counter Type = Range], [Count Direction = Up], [Step Count = 1], [Repeat = Forever] e clique em [Finish]. Ou wave modify -driver freeze -pattern counter -startvalue 0000 -endvalue 1111 -type Range -direction Up -period 120ps -step 1 -repeat forever -range 4 1 -starttime 0ps -endtime 1000ps Edit:/n_flip_flop/d
Clique sobre o sinal q na janela Objects e solte-o na janela Wave. Ao final desses passos a janela Wave deverá estar conforme mostrado abaixo: ![]()
Selecione com o shift_clique_esquerdo do mouse os sinas d e q (barramentos de 4 bits) e em seguida clique_direito e selecione [radix > unsigned]. A janela Wave deverá estar conforme mostrado abaixo: ![]()
Use os comandos da janela de transcript para criar um arquivo tb_FF.do que permite repetir de forma automatica o teste realizado. ################################
# FILE : tb_FF.do
# AUTOR: Marcos Moecke
# DATA : 14 de agosto de 2019
################################
#criacao da library work
vlib work
#compilacao da entity nome.vhd (nao necessita ser compilado no quartus II)
vcom -work work n_flip_flop.vhd
#simulacao na entity nome.vhd
vsim work.n_flip_flop
#edicao do sinal rst
wave create -pattern none -portmode in -language vhdl /n_flip_flop/rst
wave modify -driver freeze -pattern constant -value 0 -starttime 0ps -endtime 1000ps Edit:/n_flip_flop/rst
wave modify -driver freeze -pattern constant -value 1 -starttime 20ps -endtime 30ps Edit:/n_flip_flop/rst
#edicao do sinal clock
wave create -pattern none -portmode in -language vhdl /n_flip_flop/clk
wave modify -driver freeze -pattern clock -initialvalue 1 -period 100ps -dutycycle 50 -starttime 0ps -endtime 1000ps Edit:/n_flip_flop/clk
#edicao do sinal d
wave create -pattern none -portmode in -language vhdl -range N 1 /n_flip_flop/d
wave modify -driver freeze -pattern counter -startvalue 0000 -endvalue 1111 -type Range -direction Up -period 120ps -step 1 -repeat forever -range 4 1 -starttime 0ps -endtime 1000ps Edit:/n_flip_flop/d
#inclusao do sinal de saida q (como BINARY)
add wave -position end sim:/n_flip_flop/q
#inclusao do sinal de saida q (como UNSIGNED)
add wave -position end -radix hexadecimal sim:/n_flip_flop/q
#execucao da simulacao inteira
run -all
#reinicio do tempo e simulacao
restart
#execucao da simulacao por 1000 ps
run 1000 ps
|
Unidade 3 - Tipos de Dados e Operadores em VHDL
- 7 AULAS
Unidade 3 - Tipos de Dados e Operadores em VHDL | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Isso eh uma linha de comentario y <= a * b ; --o sinal y recebe o resultado da multiplicacao a x b
caracter: 'A' 'x' '#' (com aspas simples) string de caracteres: "IFSC" "teste" "teste123"
bit único: '0' '1' 'Z' (com aspas simples) vetor de bits: "0110" "101001Z" (com aspas duplas) vetor de 1 bit: "0" "1" (com aspas duplas) inteiros: 5 1101 1102 (sem aspas)
0 -> '0' 7 -> "0111" ou b"0111" ou B"0111" 1023 -> "001111111111" ou b"1111111111" ou B"1111111111"
44 -> 5*8^1 + 4*8^0 -> O"54" ou o"54" 1023 -> 1*8^3 + 7*8^2 + 7*8^1 + 7*8^0 -> o"1777" 8#1777#
1023 -> 3*16^2 + 15*16^1 + 15*16^0 = X"3FF" ou x"3FF" 16#3FF#
1023 -> 1023 ou 1_023 1000 -> 1000 ou 1_000 ou 1E3
5#320# (3*5^2 + 2*5^1 + 0*5^0) -> 85 3#201#E4 (2*3^2+0*3^1+1*3^0)*3^4 -> 1539
constant <constant_name> : <type> := <constant_value>;
A constant pode ser declarado na parte declarativa da ENTITY, ARCHITECTURE, PACKAGE, PACKAGE_BODY, BLOCK, GENERATE, PROCESS, FUNCTION e PROCEDURE. -- Signal sem valor default
-- Para atribuir um valor a um signal use "<=" como operador.
signal <name> : <type>;
-- Signal com valor default
signal <name> : <type> := <default_value>;
-- Declarações comuns de signals
signal <name> : std_logic;
signal <name> : std_logic_vector(<msb_index> downto <lsb_index>);
signal <name> : integer;
signal <name> : integer range <low> to <high>;
O signal pode ser declarado na parte declarativa da ENTITY, ARCHITECTURE, PACKAGE, BLOCK, GENERATE. Os sinais não podem ser declarados no código sequencial (PROCESS, FUNCTION e PROCEDURE), mas podem ser usados. -- Variables devem ser declarada em process ou subprogramas.
-- Para atribuir um valor a um variable use "<=" como operador.
-- Variable sem valor default.
variable <name> : <type>;
-- Variable com valor default.
variable <name> : <type> := <default_value>;
-- Declarações comuns de variables
variable <name> : std_logic;
variable <name> : std_logic_vector(<msb_index> downto <lsb_index>);
variable <name> : integer;
variable <name> : integer range <low> to <high>;
O variable (variável) só pode ser declarada e usada dentro do escopo no código sequencial (PROCESS, FUNCTION e PROCEDURE).
Exemplos de declaração de CONSTANT, SIGNAL, VARIABLE, inicializando o valor usando o agregados CONSTANT a: BIT_VECTOR(5 DOWNTO 0) := (OTHERS => '0'); -- "000000"
CONSTANT b: BIT_VECTOR(7 DOWNTO 0) := (7 => '0', OTHERS => '1'); -- "01111111"
CONSTANT c: BIT_VECTOR(7 DOWNTO 0) := (7 => '0', 6 DOWNTO 0 => '1'); -- "01111111"
CONSTANT d: BIT_VECTOR(7 DOWNTO 0) := "01111111";
SIGNAL e: STD_LOGIC_VECTOR(7 DOWNTO 0); -- Not initialized
SIGNAL f: STD_LOGIC_VECTOR(1 TO 8) := (2|3|8 => '1', 4 => 'Z', OTHERS => '0' ); -- "011Z0001"
VARIABLE g: BIT_VECTOR(1 TO 16); -- Not initialized
VARIABLE h: BIT_VECTOR(1 TO 16) := (1 TO 8 => '1', OTHERS => '0'); -- "1111111100000000"
A biblioteca standard.vhd define os tipos BIT, BIT_VECTOR, BOOLEAN, INTEGER, NATURAL, POSITIVE, CHARACTER, STRING. package standard is
type boolean is (false,true);
type bit is ('0', '1');
type severity_level is (note, warning, error, failure);
type integer is range -2147483647 to 2147483647;
type real is range -1.0E308 to 1.0E308;
type time is range -2147483648 to 2147483647
units
fs;
ps = 1000 fs;
ns = 1000 ps;
us = 1000 ns;
ms = 1000 us;
sec = 1000 ms;
min = 60 sec;
hr = 60 min;
end units;
subtype natural is integer range 0 to integer'high;
subtype positive is integer range 1 to integer'high;
type string is array (positive range <>) of character;
type bit_vector is array (natural range <>) of bit;
A biblioteca Std logic 1164.vhd define os tipos STD_(U)LOGIG, STD_(U)LOGIG_VECTOR. PACKAGE std_logic_1164 IS
TYPE std_ulogic IS ( 'U', -- Uninitialized
'X', -- Forcing Unknown
'0', -- Forcing 0
'1', -- Forcing 1
'Z', -- High Impedance
'W', -- Weak Unknown
'L', -- Weak 0
'H', -- Weak 1
'-' -- Don't care
);
TYPE std_ulogic_vector IS ARRAY ( NATURAL RANGE <> ) OF std_ulogic;
SUBTYPE std_logic IS resolved std_ulogic;
TYPE std_logic_vector IS ARRAY ( NATURAL RANGE <>) OF std_logic;
A biblioteca Std logic 1164.vhd ainda define algumas funções importantes como a rising_edge que determina se um sinal está na borda de subida (usado em sinais de clock). -------------------------------------------------------------------
-- conversion functions
-------------------------------------------------------------------
FUNCTION To_bit ( s : std_ulogic; xmap : BIT := '0') RETURN BIT;
FUNCTION To_bitvector ( s : std_logic_vector ; xmap : BIT := '0') RETURN BIT_VECTOR;
FUNCTION To_StdULogic ( b : BIT ) RETURN std_ulogic;
FUNCTION To_StdLogicVector ( b : BIT_VECTOR ) RETURN std_logic_vector;
-------------------------------------------------------------------
-- edge detection
-------------------------------------------------------------------
FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN;
FUNCTION falling_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN;
-------------------------------------------------------------------
-- edge detection
-------------------------------------------------------------------
FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
-- altera built_in builtin_rising_edge
BEGIN
RETURN (s'EVENT AND (To_X01(s) = '1') AND
(To_X01(s'LAST_VALUE) = '0'));
END;
A biblioteca Numeric std.vhd define os tipos UNSIGNED e SIGNED. package NUMERIC_STD is
type UNSIGNED is array (NATURAL range <>) of STD_LOGIC;
type SIGNED is array (NATURAL range <>) of STD_LOGIC;
A biblioteca Numeric std.vhd ainda define os operadores (abs, "+", "-", "*", "\", rem, mod, sll, slr, ror, rol), comparações ("=", '/=', ">", ">=", "<", "<=") e operadores lógicos (not, and, nand, or, nor, xor, xnor) para os tipos SIGNED e UNSIGNED. Além disso também define algumas funções muito utilizadas como: --============================================================================
-- RESIZE Functions
--============================================================================
function RESIZE (ARG: SIGNED; NEW_SIZE: NATURAL) return SIGNED;
function RESIZE (ARG: UNSIGNED; NEW_SIZE: NATURAL) return UNSIGNED;
--============================================================================
-- Conversion Functions
--============================================================================
function TO_INTEGER (ARG: UNSIGNED) return NATURAL;
function TO_INTEGER (ARG: SIGNED) return INTEGER;
function TO_UNSIGNED (ARG, SIZE: NATURAL) return UNSIGNED;
function TO_SIGNED (ARG: INTEGER; SIZE: NATURAL) return SIGNED;
Ver pag. 60 a 73 de [2]
x = "1----" -- não funciona em VHDL
std_match(x, "1----") -- funciona em VHDL
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity bin2bcd is
port
(
C : in std_logic_vector (6 downto 0);
sd, su : out std_logic_vector (3 downto 0)
);
end entity;
architecture ifsc_v1 of bin2bcd is
signal C_uns : unsigned (6 downto 0);
signal sd_uns, su_uns : unsigned (6 downto 0);
begin
sd <= std_logic_vector(resize(sd_uns, 4));
su <= std_logic_vector(resize(su_uns, 4));
sd_uns <= C_uns/10;
su_uns <= C_uns rem 10;
c_uns <= unsigned(c);
end architecture;
architecture ifsc_v2 of bin2bcd is
begin
-- Implemente o circuito usando a definição de REM que é: x REM y = x - (x/y)*y
end architecture;
configuration bin2bcd_cfg of bin2bcd is
--A instrução '''configuration''' associa a '''entity''' bin2bcd a '''architecture'''.
for ifsc_v1 end for;
--Para associar a '''entity''' bin2bcd a '''architecture''' ifsc_v2 comente a linha acima e descomente a linha abaixo.
-- for ifsc_v2 end for;
end configuration;
Figura - RTL do conversor de Binário para BCD com 2 digitos Figura - Simulação do conversor de Binário para BCD com 2 digitos
Atributos em VHDL.
Em VHDL existem diversos atributos de sintese que controlam a forma como o processo de "Analysis & Synthesis" é realizado pelo Quartus II. Uma listagem completa pode ser encontrada em:
type fruit is (apple, orange, pear, mango);
attribute enum_encoding : string;
attribute enum_encoding of fruit : type is "11 01 10 00";
entity foo is
port (sel : in std_logic;
data : in std_logic_vector(3 downto 0);
o : out std_logic);
end foo;
architecture rtl of foo is
attribute chip_pin : string;
attribute chip_pin of sel : signal is "C4";
attribute chip_pin of data : signal is "D1, D2, D3, D4";
begin
-- Specify additional code
end architecture;
O uso desse atributo sobrepõe a atribuição dos pinos através da IDE do Quartus II, e por isso não é recomendável. O atributo de síntese chip_pin pode ser usado apenas em portas da entidade "top-level" do projeto. .
O atributo de síntese KEEP, sinaliza ao processo de "Analysis & Synthesis" para manter intacto um determinado signal ou componente. signal a,b,c : std_logic;
attribute keep: boolean;
attribute keep of a,b,c: signal is true;
signal a,b,c : std_logic;
attribute preserve: boolean;
attribute preserve of a,b,c: signal is true;
signal reg1: std_logic;
attribute noprune: boolean;
attribute noprune of reg1: signal is true;
ENTITY redundant_registers IS
PORT (
clk, x: IN BIT;
y: OUT BIT);
END ENTITY;
ARCHITECTURE arch OF redundant_registers IS
SIGNAL a, b, c: BIT;
-- NORMAL -- 1 LE
--ATTRIBUTE preserve: BOOLEAN;
--ATTRIBUTE preserve OF a, b, c: SIGNAL IS TRUE; -- 2 LE
--ATTRIBUTE noprune: BOOLEAN;
--ATTRIBUTE noprune OF a, b, c: SIGNAL IS TRUE; --3 LE
--ATTRIBUTE keep: BOOLEAN;
--ATTRIBUTE keep of a,b,c: SIGNAL IS TRUE;
BEGIN
PROCESS (clk)
BEGIN
IF (clk'EVENT AND clk='1') THEN
a <= x;
b <= x;
c <= x;
END IF;
END PROCESS;
y <= a AND b;
END ARCHITECTURE;
Após a compilação do código acima, observe o número de elementos lógicos obtidos, observe o Technology Map dos circuitos gerados e verifique a localização dos FFs no Chip Planner. ![]() Fig 12. Technology Map do Circuito sem Attribute ![]() Fig 13. Technology Map do Circuito com Attribute Preserve (or Keep) ![]() Fig 14. Technology Map do Circuito com Attribute Noprune
attribute attribute_name: attribute_type;
attribute attribute_name of entity_tag [signature]: entity_class is value;
Exemplo:
Uso da instrução ALIAS.
function ADD_UNSIGNED (L, R: UNSIGNED; C: STD_LOGIC) return UNSIGNED is
constant L_LEFT: INTEGER := L'LENGTH-1;
alias XL: UNSIGNED(L_LEFT downto 0) is L;
alias XR: UNSIGNED(L_LEFT downto 0) is R;
variable RESULT: UNSIGNED(L_LEFT downto 0);
variable CBIT: STD_LOGIC := C;
begin
for I in 0 to L_LEFT loop
RESULT(I) := CBIT xor XL(I) xor XR(I);
CBIT := (CBIT and XL(I)) or (CBIT and XR(I)) or (XL(I) and XR(I));
end loop;
return RESULT;
end ADD_UNSIGNED;
|
Unidade 4 - Código Concorrente
- 4 AULAS
Unidade 4 - Código Concorrente |
---|
<optional_label>: <target> <=
<value> when <condition> else
<value> when <condition> else
<value> when <condition> else
...
<value>;
<optional_label>: with <expression> select
<target> <=
<value> when <choices>,
<value> when <choices>,
<value> when <choices>,
...
<value> when others;
CONFIGURATION which_mux OF mux IS
FOR Operator_only END FOR;
-- FOR with_WHEN END FOR;
-- FOR with_SELECT END FOR;
END CONFIGURATION;
label: FOR identificador IN faixa GENERATE
[Parte_Declarativa
BEGIN]
Instruções_concorrentes
...
END GENERATE [label];
---------------------
-- FILE my_pkg.vhd --
---------------------
library ieee;
use ieee.std_logic_1164.all;
package my_pkg is
type a_slv is array(natural range <>) of std_logic_vector (3 downto 0);
end package;
---------------------------
-- FILE vector_adder.vhd --
---------------------------
library ieee work;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use work.my_pkg.all;
entity vector_adder is
generic (N : natural := 4);
port (
a : in a_slv (0 to N-1);
soma : out std_logic_vector (3 downto 0));
end entity;
-- Versão que realiza a soma diretamente, mas que precisa modificar o código de acordo com o número de entradas.
architecture ifsc_v1 of vector_adder is
signal soma_sig : signed(3 downto 0);
begin
soma_sig <= signed(a(0)) + signed(a(1)) + signed(a(2)) + signed(a(3));
soma <= std_logic_vector(soma_sig);
end architecture;
-- Versão que realiza a soma usando um FOR GENERATE
architecture ifsc_v2 of vector_adder is
begin
end architecture;
---------------------------
-- FILE vector_adder.vhd --
---------------------------
configuration ifsc_cfg of vector_adder is
-- for ifsc_v1 end for;
for ifsc_v2 end for;
end configuration;
entity bin2gray is
generic (N : natural := 4 )
port
(
b : in std_logic_vector(____)
g : out std_logic_vector(____)
)
end entity
architecture ifsc of ____ is
begin
end architecture
entity gray2bin is
generic (N : natural := 4 )
port
(
g : in std_logic_vector(____)
b : out std_logic_vector(____)
)
end entity
architecture ifsc of ____ is
begin
end architecture
entity inc_gray is
port
(
gray_in : in std_logic_vector(____)
bray_out : out std_logic_vector(____)
)
end entity
architecture ____ of inc_gray is
begin
end architecture
function "+" (L, R: UNSIGNED) return UNSIGNED;
-- Result subtype: UNSIGNED(MAX(L'LENGTH, R'LENGTH)-1 downto 0).
-- Result: Adds two UNSIGNED vectors that may be of different lengths.
function "-" (L, R: UNSIGNED) return UNSIGNED;
-- Result subtype: UNSIGNED(MAX(L'LENGTH, R'LENGTH)-1 downto 0).
-- Result: Subtracts two UNSIGNED vectors that may be of different lengths.
function "*" (L, R: UNSIGNED) return UNSIGNED;
-- Result subtype: UNSIGNED((L'LENGTH+R'LENGTH-1) downto 0).
-- Result: Performs the multiplication operation on two UNSIGNED vectors
-- that may possibly be of different lengths.
function "/" (L, R: UNSIGNED) return UNSIGNED;
-- Result subtype: UNSIGNED(L'LENGTH-1 downto 0)
-- Result: Divides an UNSIGNED vector, L, by another UNSIGNED vector, R.
-- NOTE: If second argument is zero for "/" operator, a severity level of ERROR is issued.
|
Unidade 5 - Código Sequencial
- 7 AULAS
Unidade 5 - Código Sequencial |
---|
[rótulo:] PROCESS [(lista_de_sensibilidade)] [IS]
[parte_declarativa]
BEGIN
afirmação_sequencial;
afirmação_sequencial;
...
END PROCESS [rótulo];
[rótulo:] IF condição THEN
afirmação_sequencial;
afirmação_sequencial;
...
ELSIF condição THEN
afirmação_sequencial;
afirmação_sequencial;
...
ELSE
afirmação_sequencial;
afirmação_sequencial;
...
END IF [rótulo];
[rótulo:] LOOP
afirmação_sequencial;
afirmação_sequencial;
...
END LOOP [rótulo];
[rótulo:] FOR identificador IN faixa LOOP
afirmação_sequencial;
afirmação_sequencial;
...
END LOOP [rótulo];
[rótulo:] WHILE condição LOOP -- Executa as "afirmações enquanto a "condição" for verdadeira
afirmação_sequencial;
afirmação_sequencial;
...
END LOOP [rótulo];
[rótulo:] [FOR identificador IN faixa] LOOP
afirmação_sequencial;
EXIT [rótulo] [WHEN condição]; -- Se a "condição" é verdadeira, termina o "LOOP"
afirmação_sequencial;
...
END LOOP [rótulo];
[rótulo:] [FOR identificador IN faixa] LOOP
afirmação_sequencial;
NEXT [rótulo] [WHEN condição]; -- Se a "condição" é verdadeira, não executa as linhas até a linha "END LOOP"
-- e incrementa o "identificador".
afirmação_sequencial;
...
END LOOP [rótulo];
[rótulo:] CASE expressão IS
WHEN valor => atribuições; -- valor único
...
WHEN valor1 | valor2 | ... | valorN => atribuições; -- lista de valores
...
WHEN valor1 TO valor2 => atribuições; -- faixa de valores
...
END CASE;
|
Unidade 6 - Projeto a nível de Sistema |
---|
|
Unidade 7 - Maquinas de Estado Finitas
Unidade 7 - Maquinas de Estado Finitas |
---|
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
----------------------------------------------------------
ENTITY < entity_name > IS
PORT (
clk, rst : IN STD_LOGIC;
input : IN < data_type > ;
output : OUT < data_type >);
END < entity_name > ;
----------------------------------------------------------
ARCHITECTURE < architecture_name > OF < entity_name > IS
TYPE state IS (A, B, C, ...);
SIGNAL pr_state, nx_state : state;
ATTRIBUTE ENUM_ENCODING : STRING; --optional attribute
ATTRIBUTE ENUM_ENCODING OF state : TYPE IS "sequential";
BEGIN
------Logica Sequencial da FSM:------------
PROCESS (clk, rst)
BEGIN
IF (rst = '1') THEN
pr_state <= A;
ELSIF (clk'EVENT AND clk = '1') THEN
pr_state <= nx_state;
END IF;
END PROCESS;
------Logica Combinacional da FSM:------------
PROCESS (pr_state, input)
BEGIN
------Valores default das saidas------------
output <= < value > ;
CASE pr_state IS
WHEN A =>
output <= < value > ; -- apenas se diferente do valor default
IF (input =< value >) THEN
nx_state <= B;
...
ELSE
nx_state <= A;
END IF;
WHEN B =>
output <= < value > ; -- apenas se diferente do valor default
IF (input =< value >) THEN
nx_state <= C;
...
ELSE
nx_state <= B;
END IF;
WHEN ...
END CASE;
END PROCESS;
------Seção de Saída (opcional):-------
PROCESS (clk, rst)
BEGIN
IF (rst = '1') THEN
new_output <= < value > ;
ELSIF (clk'EVENT AND clk = '1') THEN --or clk='0'
new_output <= output;
END IF;
END PROCESS;
END < architecture_name > ;
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
----------------------------------------------------------
ENTITY < entity_name > IS
PORT (
clk, rst : IN STD_LOGIC;
input : IN < data_type > ;
output : OUT < data_type >);
END < entity_name > ;
----------------------------------------------------------
ARCHITECTURE < architecture_name > OF < entity_name > IS
TYPE state IS (A, B, C, ...);
SIGNAL pr_state, nx_state : state;
signal timer: integer range 0 to MAX;
-- ATTRIBUTE ENUM_ENCODING : STRING; --optional attribute
-- ATTRIBUTE ENUM_ENCODING OF state : TYPE IS "sequential";
BEGIN
------Logica Sequencial da FSM:------------
PROCESS (clk, rst)
variable count: integer range o to MAX;
BEGIN
IF (rst = '1') THEN
pr_state <= A;
count := 0;
ELSIF (clk'EVENT AND clk = '1') THEN
count := count + 1;
if (count >= timer) then
pr_state <= nx_state;
count := 0;
end if;
END IF;
END PROCESS;
------Logica Combinacional da FSM:------------
PROCESS (pr_state, input)
BEGIN
------Valores default das saidas------------
output <= < value >;
------Valores default do timer------------
timer <= <value>;
CASE pr_state IS
WHEN A =>
output <= < value > ; -- apenas se diferente do valor default
IF (input =< value >) THEN
timer <= <value>; -- apenas se diferente do valor default
nx_state <= B;
...
ELSE
timer <= <value>; -- apenas se diferente do valor default
nx_state <= A;
END IF;
WHEN B =>
output <= < value > ; -- apenas se diferente do valor default
IF (input =< value >) THEN
timer <= <value>; -- apenas se diferente do valor default
nx_state <= C;
...
ELSE
timer <= <value>; -- apenas se diferente do valor default
nx_state <= B;
END IF;
WHEN ...
END CASE;
END PROCESS;
------Seção de Saída (opcional):-------
PROCESS (clk, rst)
BEGIN
IF (rst = '1') THEN
new_output <= < value > ;
ELSIF (clk'EVENT AND clk = '1') THEN --or clk='0'
new_output <= output;
END IF;
END PROCESS;
END < architecture_name > ;
|
Unidade 8 - Testbench | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Unidade 8 - Testbench
---------------------------------
-- FILE: vende_balas_FSM.vhd
---------------------------------
library ieee;
use ieee.std_logic_1164.all;
entity vende_balas_FSM is
port(
rst, clk : in std_logic;
e5c, e10c, e25c: in std_logic;
d5c, d10c: out std_logic;
bala: out std_logic
);
end entity;
architecture ifsc_v1 of vende_balas_FSM is
type state is (
st0, st5, st10, st15, st20, st25, st30, st35, st40, st45
);
signal pr_state, nx_state: state;
begin
process(clk, rst)
begin
if rst = '1' then
pr_state <= st0;
elsif rising_edge(clk) then
pr_state <= nx_state;
end if;
end process;
process(pr_state, e5c, e10c, e25c)
begin
bala <= '0';
d5c <= '0';
d10c <= '0';
case pr_state is
when st0 =>
if e5c = '1' then
nx_state <= st5;
elsif e10c = '1' then
nx_state <= st10;
elsif e25c = '1' then
nx_state <= st25;
else
nx_state <= st0;
end if;
when st5 =>
if e5c = '1' then
nx_state <= st10;
elsif e10c = '1' then
nx_state <= st15;
elsif e25c = '1' then
nx_state <= st30;
else
nx_state <= st5;
end if;
when st10 =>
if e5c = '1' then
nx_state <= st15;
elsif e10c = '1' then
nx_state <= st20;
elsif e25c = '1' then
nx_state <= st35;
else
nx_state <= st10;
end if;
when st15 =>
if e5c = '1' then
nx_state <= st20;
elsif e10c = '1' then
nx_state <= st25;
elsif e25c = '1' then
nx_state <= st40;
else
nx_state <= st15;
end if;
when st20 =>
if e5c = '1' then
nx_state <= st25;
elsif e10c = '1' then
nx_state <= st30;
elsif e25c = '1' then
nx_state <= st45;
else
nx_state <= st20;
end if;
when st25 =>
bala <= '1';
nx_state <= st0;
when st30 =>
d5c <= '1';
nx_state <= st25;
when st35 =>
d10c <= '1';
bala <= '1';
nx_state <= st0;
when st40 =>
d10c <= '1';
nx_state <= st30;
when st45 =>
d10c <= '1';
nx_state <= st35;
end case;
end process;
end architecture;
|