Mudanças entre as edições de "DLP29006-Engtelecom(2020-1) - Prof. Marcos Moecke"
(→ATUAL) |
|||
Linha 1 626: | Linha 1 626: | ||
:*Ver pag. 139 a 140 de <ref name="PEDRONI2010b"/> | :*Ver pag. 139 a 140 de <ref name="PEDRONI2010b"/> | ||
+ | --> | ||
+ | {{collapse bottom}} | ||
+ | |||
+ | ===Unidade 5 - Código Sequencial=== | ||
+ | * 7 AULAS | ||
+ | {{collapse top| expand=true | Unidade 5 - Código Sequencial}} | ||
+ | ;Aula 22 (15 abr): | ||
+ | *Código Sequencial. | ||
+ | :*Diferenças entre código concorrente e sequencial <=> circuitos combinacional e sequencial | ||
+ | :*Diferenças entre os objetos SIGNAL e VARIABLE | ||
+ | :*Tipos de elementos de memória: Latch x Flip-flop | ||
+ | ::* Latch D | ||
+ | ::* Flip-flop tipo D com reset assíncrono e com reset (clear) síncrono | ||
+ | :*Seção de código sequencial '''PROCESS''': lista de sensibilidade | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [rótulo:] PROCESS [(lista_de_sensibilidade)] [IS] | ||
+ | [parte_declarativa] | ||
+ | BEGIN | ||
+ | afirmação_sequencial; | ||
+ | afirmação_sequencial; | ||
+ | ... | ||
+ | END PROCESS [rótulo]; | ||
+ | </syntaxhighlight> | ||
+ | :*Instrução '''IF''' | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [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]; | ||
+ | </syntaxhighlight> | ||
+ | :*Exemplos: | ||
+ | ::* DFFs com Reset Assincrono e Reset Sincrono, com Enable, com Preset (Variação Ex 6.1). | ||
+ | ::* Comparar com Latch (sem clk'event). | ||
+ | ::* Simulação funcional do DFFs e do Latch | ||
+ | :*Ver pag. 161 a 160 de <ref name="PEDRONI2010b"/> | ||
+ | |||
+ | <!-- | ||
+ | |||
+ | ;Aula 24 (02 out): | ||
+ | *Código Sequencial. | ||
+ | :* Contador Básico 0-N (baseado no Ex.6.2) | ||
+ | |||
+ | |||
+ | ;Aula 25 (04 out - reposição do dia 27 set): | ||
+ | * Avaliação A1 - UN2, UN3, UN4 | ||
+ | |||
+ | ;Aula 26 (07 out): | ||
+ | *Código Sequencial. | ||
+ | :* Registrador de deslocamento (Ex.6.3) | ||
+ | ::Versão 1 - Implementação com for generate da conexão de FF D. | ||
+ | ::Versão 2 - Implementação com formação de agregado via concatenação. | ||
+ | |||
+ | ;Aula 27 (09 out) | ||
+ | |||
+ | *Código Sequencial | ||
+ | :*Instruções do tipo '''LOOP''': LOOP incondicional, FOR-LOOP, WHILE-LOOP, NEXT, EXIT | ||
+ | ::*LOOP incondicional: | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [rótulo:] LOOP | ||
+ | afirmação_sequencial; | ||
+ | afirmação_sequencial; | ||
+ | ... | ||
+ | END LOOP [rótulo]; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ::*FOR-LOOP: | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [rótulo:] FOR identificador IN faixa LOOP | ||
+ | afirmação_sequencial; | ||
+ | afirmação_sequencial; | ||
+ | ... | ||
+ | END LOOP [rótulo]; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ::*WHILE-LOOP: | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [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]; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ::*LOOP com EXIT: | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [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]; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ::*LOOP com NEXT: | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [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]; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | :* Exemplos: | ||
+ | ::* Carry-Ripple Adder (FOR-LOOP) (Ex 6.4) - apenas analisar | ||
+ | ::* Leading Zeros (LOOP com EXIT) (Ex 6.5) - obter ocódigo no Moodle; fazer a síntese do circuito; fazer simulação no Modelsim; analisar a forma como o compilador implementou o incrementador. | ||
+ | :*Ver pag. 161 a 164 de <ref name="PEDRONI2010b"/> | ||
+ | |||
+ | ;Aula 28 (11 out): | ||
+ | :*Instrução '''CASE''' | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | [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; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | :*Instrução '''WAIT''': WAIT UNTIL, WAIT FOR (simulação apenas), WAIT ON (não implementada no Quartus II). | ||
+ | ::Recomenda-se utilizar a lista de sensibilidade do PROCESS e a instrução IF no lugar do WAIT. | ||
+ | ::Algumas instruções de '''WAIT''' serão utilizadas na criação de '''TestBench''' em VHDL para a simulação com o '''MODELSIM'''. | ||
+ | |||
+ | :* Timer de 0 a 9 segundos com saída SSD (Ex 6.6). | ||
+ | ::* Unir o código de um contador de 0 a 9 (código sequencial), e um conversor de binário para sete segmentos em código sequencial (usando CASE). | ||
+ | ::* Depois acrescentar um circuito que permita obter um clock com período de 1 segundo, a partir de um sinal de clock com frequência de fclk = 50MHz. | ||
+ | ::* Implementar no FPGA o circuito com contador de 0 a 9 segundos com saída SSD e clk de entrada de 50MHz. | ||
+ | :::*PROBLEMA: Uso de um período de clock de 20 ns => 50 MHz, verificar a impossibilidade prática de uma simulação deste circuito (1 segundo => 5 minutos de simulação), devido ao tamanho do contador (count1) que conta de 0 a 50M-1. | ||
+ | :::*SOLUÇÃO: modificar o contador para um valor máximo menor (0 a 50-1). Notar que a simulação é extremamente rápida neste caso. | ||
+ | :::*Após verificar que o circuito funciona "simulado", configurar o FPGA do kit Mercúrio IV para implementar este circuito. As informações necessárias estão em [[Preparando para gravar o circuito lógico no FPGA]]. Utilize os pinos (clk = CLOCK_50MHz: PIN_T1, led = DISP0_D[7] : PIN_W1, ssd = DISP0_D[0-6]: PIN_V2 - PIN_W2). | ||
+ | :::* Como o conversor de binário para ssd realizado anteriormente tinha lógica negativa ('0' acende, '1' apaga), será necessário inverter todas as saídas | ||
+ | ssd_out <= not ssd; | ||
+ | :::*Se quiser usar um led na matriz de led é necessário colocar '0' da coluna do Led e '1' na linha correspondente, ou seja utilizar um segundo pino para acender o led. | ||
+ | |||
+ | ;Aula 29 (14 out): | ||
+ | *Uso do Modelsim para simulação funcional. | ||
+ | :*Use o Modelsim para fazer a simulação do circuito do timer de 0 a 9 segundos. | ||
+ | :*Ver [[Seguindo o tutorial da ALTERA para o MODELSIM]], para utilizar o básico do MODELSIM. | ||
+ | :* [http://www.vhdl.us/Book_VHDL_2ed_unrestricted/Pedroni_VHDL_2ed_tutorial_ModelSim_10.1d_v2.pdf Pedroni VHDL 2ed Tutorial of ModelSim 10.1d] | ||
+ | :* [https://www.youtube.com/watch?v=Z8whdGa7RtY ModelSim Video Tutorial] - Kirk Weedman | ||
+ | :*[[Media:modelsim_tut.pdf |ModelSim® Tutorial]] -v10.0d | ||
+ | :* [[Documentação do ModelSim]], para conhecer mais a fundo o MODELSIM. | ||
+ | --> | ||
+ | <!-- | ||
+ | *Projete um contador BCD de 00 a 99 configurável. | ||
+ | ::Efetue a simulação funcional (Usando o QSIM e o Modelsim) fazendo a contagem de 00 a 11 e 00 a 23 (para hora) , de 00 a 59 (para minutos e segundos), e de 00 a 99. | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | entity Count00_99 is | ||
+ | port ( | ||
+ | clk : in std_logic; | ||
+ | bcd_U : out std_logic_vector(3 downto 0); | ||
+ | bcd_D : out std_logic_vector(3 downto 0) | ||
+ | ); | ||
+ | end entity; | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | *Implementação de um relógio contador BCD de segundos. | ||
+ | :*Utilizando o sistema anterior, inclua um contador em BCD de dois dígitos que permita fazer a contagem de 00 a 99, onde o valor final é configurável. | ||
+ | ::Efetue a simulação funcional (Usando o QSIM e o Modelsim) fazendo a contagem de 00 a 11 e 00 a 23 (para hora) , de 00 a 59 (para minutos e segundos), e de 00 a 99. | ||
+ | <syntaxhighlight lang=vhdl> | ||
+ | entity Timer00_99seg is | ||
+ | port ( | ||
+ | clk50MHz : in std_logic; | ||
+ | clk1seg : out std_logic; | ||
+ | SSD_Useg : out std_logic_vector(0 to 6); | ||
+ | SSD_Dseg : out std_logic_vector(0 to 6) | ||
+ | ); | ||
+ | end entity; | ||
+ | </syntaxhighlight> | ||
+ | ::configure o FPGA do kit Mercúrio IV para implementar este circuito. Utilize os mostradores ssd DISP0_D e DISP1_D. | ||
+ | *Projeto e simulação com Modelsim do sistema Timer00-99 com display de 7 segmentos e divisor de clock. | ||
+ | *Na simulação definir o clk50MHz como 100ms para produzir um clk1sec com duração de 1 segundo. | ||
+ | *Corrigir o primeiro período de clock de clk1sec. É necessário fazer com que o sinal seja alto primeiro e depois vá para baixo de modo a garantir que a transição positiva ocorra depois de 1 segundo. | ||
+ | *'''IMPORTANTE''': Também é necessário incluir um RESET em cada circuito que seja sequencial. Também é necessário iniciar o circuito com um reset de 10 ps na simulação. | ||
+ | *Perceber a necessidade de parametrizar o conversor de bcd2ssd para permitir displays do tipo CA e AA. (ler [[Display de 7 segmentos]]) | ||
+ | *Perceber a necessidade de incluir um sinal que indique o final da contagem no counter00_99. Esse sinal poderá ser usado como clock no relógio a ser projetado. | ||
--> | --> | ||
{{collapse bottom}} | {{collapse bottom}} |
Edição das 14h49min de 15 de abril de 2020
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
|
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;
library ieee;
use ieee.std_logic_1164.all;
entity tri_state is
generic (N: NATURAL := 1);
port
(
input : in std_logic_vector(N-1 downto 0);
ena : in std_logic;
output : out std_logic_vector(N-1 downto 0);
);
end entity;
architecture tri_state of tri_state is
begin
output <= input when ena = '1' else "Z";
end architecture;
library ieee;
use ieee.std_logic_1164.all;
entity Ex3_2 is
port
(
x : in STD_LOGIC_VECTOR(1 downto 0);
y : out STD_LOGIC_VECTOR(1 downto 0)
);
end entity;
architecture un3 of Ex3_2 is
begin
y <= "00" when x = "00" else
"01" when x = "10" else
"10" when x = "01" else
"--";
end architecture;
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 INICIO DAS AULAS REMOTAS SÍNCRONAS
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;
attribute attribute_name: attribute_type;
attribute attribute_name of entity_tag [signature]: entity_class is value;
type a1Dx1D_bit is array (1 to 3) of BIT_VECTOR(1 to 4);
type a2D_bits is array (1 to 3, 1 to 4) of bit; type a3D_bits is array (1 to 3, 1 to 4, 1 to 2) of bit;
slice3 <= table(row, 1) & table(row, 2) & & table(row, 3) & & table(row, 4);
slice4 <= table(1, column) & table(2, column) & table(3, column);
gen1 : for j in 1 to 4 generate
slice3(j) <= table(row, j);
end generate;
gen2 : for i in 1 to 3 generate
slice4(i) <= table(i, column);
end generate;
a_UNS <= unsigned(a_SLV); a_SIG <= signed(a_SLV);
a_INT <= to_integer(a_UNS)); a_INT <= to_integer(a_SIG));
a_SLV <= std_logic_vector(a_UNS); a_SLV <= std_logic_vector(a_SIG);
a_UNS <= to_unsigned(a_INT,NBITS)); a_SIG <= to_signed(a_INT, NBITS));
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.
function "rem" (L, R: UNSIGNED) return UNSIGNED;
-- Result subtype: UNSIGNED(R'LENGTH-1 downto 0)
-- Result: Computes "L rem R" where L and R are UNSIGNED vectors.
function "mod" (L, R: UNSIGNED) return UNSIGNED;
-- Result subtype: UNSIGNED(R'LENGTH-1 downto 0)
-- Result: Computes "L mod R" where L and R are UNSIGNED vectors.
Nesta aula vamos estudar algumas estruturas e dicas adicionais para a sintese de circuitos em VHDL
Enquanto que em um ARRAY todos os elementos devem ser obrigatoriamente do mesmo tipo, em um RECORD (Registro) os elementos podem ser de tipos diferentes. type memory_access is record
address : integer range 0 to 255;
block : integer range 0 to 3;
data : BIT_VECTOR(15 downto 0);
end record;
--Escrita no RECORD
constant endereco : memory_access := (34, 3, "010011110101011");
--Acesso ao RECORD
signal address_lido : integer range 0 to 255;
signal block_lido : integer range 0 to 3;
signal data_lido : bit_vector(15 downto 0);
address_lido <= endereco.address;
block_lido <= endereco.block;
data_lido <= endereco.data;
entity record_example is
port (
flag : out BIT_VECTOR(1 to 4);
sum : out natural range 0 to 15
);
end entity;
architecture record_example of record_example is
type pair is record
a, b : natural range 0 to 7;
end record;
type stack is array (1 to 4) of pair;
constant matrix : stack := ((1, 2), (3, 4), (5, 6), (7, 0));
begin
gen : for i in 1 to 4 generate
flag(i) <= '1' when matrix(i).a > matrix(i).b else '0';
end generate;
sum <= matrix(1).a + matrix(1).b;
end architecture;
A declaração de SUBTYPE é usada para restringir as declarações de TYPE. Abaixo estão alguns exemplos. subtype natural is integer range 0 to integer'HIGH;
subtype positive is integer range 1 to integer'HIGH;
subtype my_integer is integer range - 32 to 31;
-----Package:------------
-- File: my_pkg.vhd
-------------------------
package my_data_types is
type a1Dx1D_bit_vector is array (0 to 3) of BIT_VECTOR(7 downto 0);
end my_data_types;
-----Main code: --------
-- File: my_pkg.vhd
-------------------------
use work.my_data_types.all;
entity mux1Dx1D is
port (
x : in a1Dx1D_bit_vector;
sel : integer range 0 to 3;
y : out BIT_VECTOR(7 downto 0)
);
end entity;
architecture pedroni of mux1Dx1D is
begin
y <= x(sel);
end architecture;
Ver pag. 60 a 73 de [2]
A declaração ALIAS define um nome alternativo para uma entidade ou objeto. ALIAS new_name [: specifications] IS original_name [signature];
SIGNAL data_bus: STD_LOGIC_VECTOR(31 DOWNTO 0);
--bus1 is a new name for data_bus:
ALIAS bus1 IS data_bus;
--bus2 is a new name for data_bus, but with a modified range:
ALIAS bus2: STD_LOGIC_VECTOR(32 DOWNTO 1) IS data_bus;
--bus3 is another name for data_bus, with an ascending range:
ALIAS bus3: STD_LOGIC_VECTOR(1 TO 32) IS data_bus;
--upper_bus1 is a new name for the upper half of data_bus
ALIAS upper_bus1 IS data_bus(31 DOWNTO 16);
--upper_bus2 is a new name for the upper half of data_bus, but
--with a modified range:
ALIAS upper_bus2: STD_LOGIC_VECTOR(17 TO 32) IS data_bus(31 DOWNTO 16);
--lower_bus1 is a new name for the lower half of data_bus
ALIAS lower_bus1 IS data_bus(15 DOWNTO 0);
--lower_bus2 is a new name for the lower half of data_bus, but
--with a modified range:
ALIAS lower_bus2: STD_LOGIC_VECTOR(1 TO 16) IS data_bus(15 DOWNTO 0);
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;
function "+" (a : integer, b : bit) return integer is
begin
if (b = '1') then return a + 1;
else
return a;
end if;
end "+";
|
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>;
Warning (13012): Latch ... has unsafe behavior
<optional_label>: with <expression> select
<target> <=
<value> when <choices>,
<value> when <choices>,
<value> when <choices>,
...
<value> when others;
Error (10313): VHDL Case Statement error ...: Case Statement choices must cover all possible values of expression
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;
-------------------------
-- File: gray2bin.vhd --
-------------------------
entity gray2bin is
generic (N : natural := 4 )
port
(
g : in std_logic_vector(____)
b : out std_logic_vector(____)
)
end entity
architecture ifsc_v1 of ____ is
begin
end architecture
architecture ifsc_v2 of ____ is
begin
end architecture
----------------------
-- File: alu.vhd --
----------------------
entity alu is
generic (N : natural := 8);
port
(
a, b : in std_logic(? downto 0);
cin : in std_logic;
opcode : in std_logic(? downto 0);
y : out std_logic(? downto 0)
);
end entity;
architecture alu of alu is
begin
end architecture;
FONTE: pag. 127 [2]
|
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];
|
Avaliações
Atividade Relâmpago (AR)
As atividades relâmpago são atividades avaliativas opcionais que darão BôNUS adicionais ao aluno na próxima avaliação. Elas normalmente consistem de soluções simples para algum problema ou sistema. Elas são enunciadas na aula, e o prazo e a entrega serão definidos no Moodle. Não são aceitas entregas tardias, e apenas 2 alunos podem receber o bonus. A pontuação das atividades é informada a cada atividade.
Avaliação A1
- Conteúdo avaliado serão as unidades 2 a 4 (cap 1 - 5)
- Data da avaliação (xx/xx/2020) - Local: LabSiDi.
Avaliação A2
- Conteúdo avaliado serão as unidades 5 a 8 (Cap 6 a 10)
- Data da avaliação (xx/xx/2020) - Local: LabSiDi.
Recuperação R12
- Esta avaliação somente será realizada se necessária, e deverá ser feita na última semana letiva do semestre
- Conteúdo avaliado será as unidades 2 a 8
- Data da avaliação (XX/XX/2020) - Local: LabSiDi.
- As avaliações A1 e A2 são com consulta apenas as folhas de consulta entregues:
- VHDL Quick Reference - SynthWorks
- VHDL Types and Operators Quick Reference - SynthWorks
- ModelSim Quick Reference - SynthWorks
- Tabelas das figuras 3.6, 3.10 e 4.1 do livro do Pedroni.
- Arquivo:Numeric std conversions.png
- Dica use também como fonte de consulta os templates do Quartus.
- Ao final das avaliações o aluno deverá enviar a avaliação para a plataforma Moodle com os arquivos solicitados.
Estudos livres sem entrega de documentação (EL)
- Os estudos livres são fortemente recomendados aos alunos como forma de melhor compreender o assunto estudado em cada unidade. Nas listas de exemplos e exercícios, os essenciais estão destacados em negrito. Não há prazos nem entregas desses estudos no Moodle, mas pede-se que os alunos realizem esses estudos e tirem suas dúvidas nas aulas destinadas a resolução de exercícios, ou nos minutos iniciais das aulas.
EL1 - Resolução dos exercícios do Cap 2 |
---|
|
EL2 - Resolução dos exercícios do Cap 3 |
---|
|
EL3 - Resolução dos exercícios do Cap 4 |
---|
|
EL4 - Resolução dos exercícios do Cap 5 |
---|
|
Referências Bibliográficas:
- ↑ PEDRONI, Volnei A. Eletrônica digital moderna e VHDL; 1ª ed. Rio de Janeiro:Elsevier, 2010. 619p. . ISBN 9788535234657
- ↑ 2,00 2,01 2,02 2,03 2,04 2,05 2,06 2,07 2,08 2,09 2,10 2,11 PEDRONI, Volnei A. Circuit Design and Simulation with VHDL; 2ª ed. Massachusetts-EUA:MIT, 2010. 608 p. ISBN 9780262014335