Sei sulla pagina 1di 57

TECNOLOGA Y DISEO MICROELECTRNICO 1

TEMA 2.2
SENTENCIAS Y MODELOS

TEMA 2.2 SENTENCIAS Y MODELOS

TIPOS DE SENTENCIAS

SECUENCIALES

CONCURRENTES

WAIT
Asignacin de variable
Asignacin de seal simple(1)
IF
CASE
NULL

Asignacin de seal simple (1)


Asignacin de seal selectiva
Asignacin de seal condicional
Procesos
Instancia de componentes

LOOP
NEXT
EXIT
RETURN
Llamada a Procedimientos (1)
ASSERT (1)

Llamada a Procedimientos (1)


ASSERT (1)
BLOCK
GENERATE

(1) Estas

sentencias pueden aparecer tanto en el mbito secuencial como en el mbito


concurrente

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (I)
Asignacin Simple, Selectiva y Condicional: Van fuera de un process
Asignacin de seal simple. Ejemplo:
A <= "1010";
B <= 3;
Asignacin de seal selectiva. Ejemplo: (multiplexor)
with s select salida <=
d0 when "00",
d1 when "01",
d2 when "10",
d3 when "11";
A partir de los valores de s se asigna valor a salida
Asignacin de seal condicional. Ejemplo:
b <= "1000" when a = "00" else
0100" when a = "01" else
0010" when a = "10" else
0001" when a = "11";

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (II)
Ejemplos de asignacin concurrente :

architecture concurrente of eqcomp is


begin
Iguales <= 1 when (A = B) else 0;
end concurrent;

architecture concurrente of eqcomp2 is


begin
Iguales<= (A(0) xnor B(0)) and
(A(1) xnor B(1)) and
(A(2) xnor B(2)) and
(A(3) xnor B(3));
end concurrent;

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (III)
Process:

Sentencia concurrente que define su comportamiento a travs de


sentencias secuenciales. Permite crear bucles infinitos.

Sintaxis:
[etiqueta :] process [(lista de sensibilidad)]
Declaraciones de variables, procedimientos o tipos, pero no seales
begin
sentencias_secuenciales;
end process [etiqueta];
Una arquitectura puede tener tantos procesos como se quiera, todos ejecutndose
en paralelo
Han de tener obligatoriamente un mecanismo de detencin/reactivacin (lista de
sensibilidad o sentencia WAIT)
Las instrucciones dentro del proceso se ejecutan secuencialmente, una detrs de
otra, pero sin dar lugar a que avance el tiempo durante su ejecucin
El tiempo slo avanza cuando se llega al final del proceso o ste se suspende

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (IV)
Retardo delta:
Este mecanismo se introduce para permitir la simulacin de hardware (paralelo
por naturaleza) usando mquinas secuenciales
Un retardo delta no implica actualizar o cambiar el tiempo de simulacin, pero
s que implica ejecutar un nuevo ciclo de simulacin.
Modela el retardo entre el momento en que un proceso coloca un nuevo valor
en la cola de eventos de una seal (el proceso ejecuta la asignacin sobre la
seal) y el momento en que esta seal toma el valor programado en la cola de
eventos.
Ejemplo:
ENTITY timing IS
(PORT(a,b : IN BIT; z,zbar : OUT BIT);
END ENTITY;
ARCHITECTURE delta of timing IS
BEGIN
zbar <= NOT z;
z <= a AND b AFTER 10 NS;
END delta;

o z cambia 10 ns despus de a b
o zbar cambia 10ns+ despus de a b
o slo es vlido internamente en el simulador
o Externamente z y z bar cambian a la vez,
10 ns despus de a b

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (V)
Ejemplo procesos:
entity ORGATE is
port (A, B: in BIT;Z: out BIT);
end ORGATE;
architecture BEHAVE of ORGATE is
Begin
OR_FUNC: process (A,B)
begin
if (A='1' or B='1') then
Z <= '1';
else
Z <= '0';
end if;
end process OR_FUNC;
end BEHAVE;

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (VI)
Ejemplo procesos:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity cnt1 is
port ( clk,rst : in std_logic;
salida : out std_logic_vector(3 downto 0));
end cnt1;
architecture B2 of cnt1 is
begin
process (clk,rst)
variable cuenta:unsigned(3 downto 0);
begin
if (rst='1') then
cuenta:= (others=> '0');
elsif (clk'event and clk='1') then
cuenta:= cuenta+1;
end if;
salida<=std_logic_vector(cuenta);
end process;
end B2;

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (VII)
Declaracin e Instancia de componentes: Permiten realizar descripciones
estructurales y diseos jerrquicos
La declaracin puede aparecer en una arquitectura o en un paquete
Sintaxis de declaracin de un componente:
component nombre_componente
[generic (lista_generic);]
[port (lista_puertos);]
end component [nombre_componente];
Instancia de componentes: Es un instruccin concurrente que especifica la
interconexin de las seales del componente dentro del diseo en el que est
siendo utilizado.
Sintaxis de instancia de un componente:
etiqueta_referencia : nombre_componente
[generic map (lista_asociacin);]
[port map (lista_asociacin);]

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (VIII)
Ejemplo de Declaracin e Instancia de componentes:
entity GNAND2 is
port ( A: in BIT; B: in BIT; -- A,B: in BIT;
C: out BIT );
end GNAND2;
architecture PRIMERA of GNAND2 is
begin
C <= not (A and B); -- sent. asignacion a senial
end PRIMERA;
architecture DELAY of GNAND2 is
begin
C <= A nand B after 2 NS;
end;

entity GINVER is
port (A: in BIT; B: out BIT );
end GINVER;
architecture FUNCIONAL of GINVER is
begin
B <= not A;
end FUNCIONAL;
architecture DELAY of GINVER is
begin
B <= not A after 1 NS;
end DELAY ;

TEMA 2.2 SENTENCIAS Y MODELOS

Ejemplo de Declaracin e Instancia de componentes:

CONCURRENTES (IX)
entity LATCHD is
port (D, L: in BIT; Q, QN: out BIT );
end LATCHD;
architecture ESTRUCTURAL of LATCHD is
component NAND2
port ( A, B: in BIT; C: out BIT );
end component;
component INVER
port ( A: in BIT; B: out BIT );
end component;
for U0: INVER use entity WORK.GINVER(FUNCIONAL);
for all: NAND2 use entity WORK.GNAND2(PRIMERA);
signal DN, R, S, Qi, Qni: BIT;
begin
U0: INVER port map ( D, DN );
U1: NAND2 port map ( D, L, S );
U2: NAND2 port map ( DN, L, R );
U3: NAND2 port map ( S, QNi, Qi );
U4: NAND2 port map ( R, Qi, QNi );
Q <= Qi; QN <= QNi;
end ESTRUCTURAL;

TEMA 2.2 SENTENCIAS Y MODELOS

Ejemplo de Declaracin e Instancia de componentes:

CONCURRENTES (IX)
entity LATCHD is
port (D, L: in BIT; Q, QN: out BIT );
end LATCHD;
architecture ESTRUCTURAL of LATCHD is
component NAND2
port ( A, B: in BIT; C: out BIT );
end component;
component INVER
port ( A: in BIT; B: out BIT );
end component;
for U0: INVER use entity WORK.GINVER(FUNCIONAL);
for all: NAND2 use entity WORK.GNAND2(PRIMERA);
signal DN, R, S, Qi, Qni: BIT;
S
begin
D
U0: INVER port map ( D, DN );
U1: NAND2 port map ( D, L, S );
U2: NAND2 port map ( DN, L, R );
L
U3: NAND2 port map ( S, QNi, Qi );
U4: NAND2 port map ( R, Qi, QNi );
DN
Q <= Qi; QN <= QNi;
R
end ESTRUCTURAL;

Q
Q

QN

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (X)
Llamada a subprogramas (procedimientos o funciones): Dicha llamada puede
hacerse de forma secuencial o concurrente en funcin de dnde se escriba la
sentencia
Sintaxis:
nombre_procedimiento_o_funcin [{parmetros, }];
Ejemplo:
PROCEDURE lee(longitud : IN integer := 200) IS
BEGIN
....
END PROCEDURE;
-- Posible llamada
lee(350);

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (XI)
ASSERT: Sentencia que comprueba si se cumple una condicin y genera un mensaje
si no se cumple
Sintaxis:
ASSERT condicion REPORT string SEVERITY nivel;
La expresin que se pone tras REPORT debe de ser de tipo string y el el mensaje que
se presenta si no se cumple la condicin
Tipos de SEVERITY: NOTE, WARNING, ERROR (por defecto si no se especifica), y
FAILURE

BLOCK: Es una forma de agrupar sentencias concurrentes en una arquitectura.


Puede emplearse para mejorar la legibilidad del cdigo.
Sintaxis:
label: block (optional_guard_condition)
Declarations
begin
sentencias concurrentes
end block label;

TEMA 2.2 SENTENCIAS Y MODELOS

CONCURRENTES (XII)
GENERATE: Permite crear estructuras repetitivas y regulares. Se suele emplear para
instanciar componentes idnticos bajo el control de un ndice o de una condicin .
Sintaxis:
label: for parameter in range generate
concurrent statements
end generate label;
Ejemplo:
entity FULL_ADD4 is
port(A, B : in BIT_vector(3 downto 0); CIN : in BIT;
SUM : out BIT_vector(3 downto 0); COUT : out BIT);
end FULL_ADD4;
architecture USO_GENERATE of FULL_ADD4 is
component FULL_ADDER
port(PA, PB, PCin : in BIT; PSUM, PCOUT: out BIT);
end component;
signal CAR : BIT_vector(4 downto 0);

begin
CAR(0) <= CIN;
GK : for K in 3 downto 0 generate
FA : FULL_ADDER port map(A(K),
B(K), CAR(K), SUM(K), CAR(K+1));
end generate GK;
COUT <= CAR(4);
end USO_GENERATE;

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (I)
WAIT: Es una sentencia secuencial, por lo que slo puede aparecer en el cuerpo de
un PROCESO.
Es un mecanismo de control de la ejecucin de dicho proceso (suspende y reactiva
la ejecucin del mismo )
SINTAXIS:
wait [on LISTA] [until CONDICION] [for TIEMPO];
Sin opciones, no hay condicin de reactivacin, el proceso queda suspendido
indefinidamente:
wait;
Con opcin de reactivacin simple:
wait on A; -- Evento en la seal A
wait until B; - La condicin B pasa a ser TRUE
wait for X NS; -- Transcurrido X NS de tiempo simulado

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (II)
Asignacin de Variables: Las variables slo pueden declararse y utilizarse dentro
de procesos o subprogramas.
La asignacin se realiza con :=
Se puede asignar un valor inicial a la variable al realizar la declaracin
Ejemplo:
Process ()
variable Estado: bit:=0; --definicin y asignacin inicial
begin
Estado:= 1;

Las asignaciones al nuevo valor, a diferencia de las seales, tienen lugar


inmediatamente

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (III)
Diferencia entre seales y variables en asignacin de valores:
SIG: process

ID_SIGNAL <= EXPRESION [ after X NS ];


-- asignacin retardada, al menos un DELTA
ID_VARIABLE := EXPRESION; -- inmediata
entity E is end E;
architecture A of E is
signal N, SUMA: INTEGER := 0;
begin
VAR: process
variable NV, SUMAV: INTEGER := 0;
begin
wait for 10 NS; NV := NV + 1;
SUMAV := SUMAV + NV;
end process VAR;
SIG: process
begin
wait for 10 NS; N <= N + 1;
SUMA <= SUMA + N;
end process SIG;
end A;

VAR: process

ns delta

SUMA

NV

SUMAV

+0

10

+0

10

+1

20

+0

20

+1

30

+0

30

+1

40

+0

10

40

+1

10

50

+0

15

50

+1

10

15

60

+0

10

21

60

+1

15

21

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (IV)
IF: Permite la ejecucin de sentencias en funcin del cumplimiento de ciertas
condiciones.
SINTAXIS:

if ... then
S1; S2; ...; SN;
end if;

if ... then
R1; R2; ...; RN;
else
S1; S2; ...; SN;
end if;

if ... then
R1; R2; ...; RN;
elsif ... then
S1; S2; ...; SN;
elsif ... then
T1; T2; ...; TN;
else
W1; W2; ...; WN;
end if;

Est permitido el uso de IFs anidados, pero es recomendable utilizar las clausulas
ELSIF pues tienen una interpretacin ms simple.

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (V)
CASE: A partir del valor de una expresin permite seleccionar una y slo una de un
conjunto de opciones posibles
SINTAXIS:
case EXPRESION is
when VALOR => -- un valor simple
S1;S2;...;SN;
when VALOR1 | VALOR2 | VALOR3 => -- un conjunto de valores
S1;S2;...;SN;
when VALOR4 to VALOR5 => -- un rango de valores
S1;S2;...;SN;
when others => -- resto de valores no cubiertos
S1;S2;...;SN; -- en la otras opciones
end case;
Las distintas opciones que aparecen deben cubrir todos los posibles valores que
puede generar la evaluacin de la expresin.

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (VI)
Ejemplo sentencia CASE:
entity BCD2LED is
port ( BCD: in BIT_VECTOR(3 downto 0); LED: out BIT_VECTOR(6 downto 0);
end BCD2LED;
architecture F of BCD2LED is
begin
process (BCD)
begin
case BCD is
when "0000" => LED <= "1111110"; -- abcdefg -when "0001" => LED <= "1100000";
when "0010" => LED <= "1011011";
when "0011" => LED <= "1110011";
when "0100" => LED <= "1100101";
when "0101" => LED <= "0110111";
when "0110" => LED <= "0111111";
when "0111" => LED <= "1100010";
when "1000" => LED <= "1111111";
--completar lo que falta
end case;
end process;
end;

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (VII)
Ejemplo sentencia CASE:
entity BCD2LED is
port ( BCD: in BIT_VECTOR(3 downto 0); LED: out BIT_VECTOR(6 downto 0);
end BCD2LED;
architecture F of BCD2LED is
begin
process (BCD)
begin
case BCD is
when "0000" => LED <= "1111110"; -- abcdefg -when "0001" => LED <= "1100000";
when "0010" => LED <= "1011011";
when "0011" => LED <= "1110011";
when "0100" => LED <= "1100101";
when "0101" => LED <= "0110111";
when "0110" => LED <= "0111111";
when "0111" => LED <= "1100010";
when "1000" => LED <= "1111111";
when "1001" => LED <= "1110111";
when others => LED <= "0000000";
PENSAR EL CASO HEX2LED!
end case;
end process;
end;

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (VIII)
NULL: No realiza funcin alguna. Pasa la ejecucin a la siguiente sentencia
secuencial.

til en sentencias CASE cuando no se quiere realizar ninguna accin para


alguna de las elecciones. Ejemplo: when others => null;
Sintaxis:
[etiqueta:] NULL;
LOOP: Se utiliza para realizar bucles. Va acompaada de sentencias FOR o WHILE

Sintaxis:
[etiqueta:] [FOR identificador IN rango| WHILE condicion] LOOP
secuencias secuenciales
END LOOP [etiqueta];

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (IX)
LOOP: Ejemplos:
process (A)
begin
Z <= "0000";
for I in 0 to 3 loop
if (A = I) then
Z(I) <= '1';
end if;
end loop;
end process;

process (A)
variable I : integer range 0 to 4;
begin
Z <= "0000";
I := 0;
while (I <= 3) loop
if (A = I) then
Z(I) <= '1';
end if;
I := I + 1;
end loop;
end process;

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (X)
NEXT: Dentro de una sentencia Loop, detiene la ejecucin de la iteracin actual y
pasa a la siguiente iteracin

Sintaxis:
[etiqueta:] NEXT [identificador bucle] [WHEN condicin];

Ejemplo:
--Interrumpe el FOR y sigue por el WHILE
termina: WHILE a< 100 LOOP
--- sentencias
sigue: FOR n IN 0 TO 100
--- sentencias
NEXT termina WHEN n=a;
END LOOP sigue;
END LOOP termina;

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (XI)
EXIT: Dentro de una sentencia Loop, detiene la ejecucin en ese instante y sale del
bucle

Sintaxis:
[etiqueta:] EXIT [identificador bucle] [WHEN condicin];

Ejemplo:
for I in 0 to 7 loop
if FINISH_LOOP_EARLY = '1' then
exit;
else
A_BUS <= TABLE(I);
wait for 5 ns;
end if;
end loop;

TEMA 2.2 SENTENCIAS Y MODELOS

SECUENCIALES (XII)
RETURN: Slo puede aparecer en subprogramas, y fuerza la vuelta de los mismos
al programa que lo llama.

Sintaxis:
[etiqueta:] RETURN[expresion] ;
RETURN es opcional dentro de un procedimiento y no puede contener una
expresin. Fuerza la salida del procedimiento antes de llegar al final.
Una funcin tiene que contener obligatoriamente un RETURN y una expresin
Ejemplo:
FUNCTION es_uno(din : std_logic_vector(31 downto 0)) RETURN std_logic IS
VARIABLE val : std_logic;
BEGIN
IF din = X"00000001" THEN
val := '1';
ELSE
val := '0';
END IF;
RETURN val;
END es_uno;

TEMA 2.2 SENTENCIAS Y MODELOS

SUBPROGRAMAS (I)
Un subprograma es una funcin o procedimiento que realiza una determinada
tarea, y que ayudan a estructurar y reutilizar el cdigo.
Puede declararse en un paquete, o localmente en la parte declarativa de una
arquitectura, de un bloque o proceso.
Una funcin devuelve un valor y un procedimiento devuelve los valores a travs de
los parmetros que le han sido pasados como argumentos.
A consecuencia de la anterior, en una funcin todos sus parmetros son de entrada,
por el contrario en un procedimiento los parmetros pueden ser de entrada, de
salida o de entrada y salida.
Las funciones debern contener la palabra reservada RETURN, mientras que los
subprogramas no tienen necesidad de disponer dicha sentencia.
Las funciones se usan en expresiones, sin embargo, los procedimientos se llaman
como una sentencia secuencial o concurrente.
Las funciones nunca pueden tener una sentencia WAIT, pero los procedimientos s.

TEMA 2.2 SENTENCIAS Y MODELOS

SUBPROGRAMAS (II)
Sintaxis:
function nombre_funcion [ (lista_parametros)] return tipo is
{declaraciones}
begin
{sentencias secuenciales}
end nombre_funcion;

procedure nombre_procedimiento [(lista_parametros)] is


{parte declarativa}
begin
{sentencias secuenciales}
end nombre_procedimiento;

TEMA 2.2 SENTENCIAS Y MODELOS

SUBPROGRAMAS (III)
Los procedimientos pueden tener en el encabezado parmetros de tipo in,
out o inout
Estos parmetros pueden ser seales, variables o constantes
El tipo por defecto (si no se especifica) para parmetros de tipo in es una
constante.
La llamada en los de tipo constante de entrada se puede hacer desde un
literal, una constante, una seal o una expresin
El tipo por defecto (si no se especifica) para parmetros de tipo out e inout
es una variable
Si el de salida es una variable, el que lo llama tambin ha de serlo.
Si el de salida es una seal, el que lo llama tambin ha de serlo.

TEMA 2.2 SENTENCIAS Y MODELOS

SUBPROGRAMAS (IV)
Ejemplos:
FUNCTION es_uno(din : std_logic_vector(31 downto 0)) RETURN std_logic IS
VARIABLE val : std_logic;
BEGIN
IF din = X"00000001" THEN
val := '1';
ELSE
val := '0';
END IF;
RETURN val;
END es_uno;
PROCEDURE es_uno(din : in std_logic_vector(31 downto 0); dout : out std_logic) IS
BEGIN
IF din = X"00000001" THEN
dout := '1';
ELSE
dout := '0';
END IF;
END es_uno;

TEMA 2.2 SENTENCIAS Y MODELOS

SUBPROGRAMAS (V)
Ejemplos de llamadas:
PROCEDURE limite(CONSTANT conj : IN std_logic_vector(3 DOWNTO 0);
VARIABLE min, max : INOUT integer) IS ...
Llamada implcita:
limite(cjt(31 DOWNTO 28), valmin, valmax);
Llamada explcita:
limite(min=>valmin, max=>valmax, conj=>cjt(31 DOWNTO 28));
PROCEDURE lee (longitud : IN integer := 200) IS BEGIN ....
END PROCEDURE;
-- Posibles llamadas
lee;
lee(350);

TEMA 2.2 SENTENCIAS Y MODELOS

ESTILOS DE DESCRIPCIN DE CIRCUITOS EN VHDL


ALGORTMICO: El circuito se describe como en un programa software, reflejando
la funcionalidad del mdulo, componente o circuito, en forma de uno o ms
procesos concurrentes que contienen descripciones secuenciales del algoritmo
correspondiente.

FLUJO DE DATOS: Descripcin basada en ecuaciones o expresiones que reflejan el


flujo de informacin y las dependencias entre datos y operaciones. Ejemplo
empleando sentencias concurrentes del tipo: When else o With select

ESTRUCTURAL: Descripcin en base a referencia de componentes y conexiones


entre ellos a travs de sus puertos de entrada/salida.

MIXTO: Descripcin en base a una mezcla de los anteriores.

TEMA 2.2 SENTENCIAS Y MODELOS

GENERACIN DE ESTMULOS EN VHDL (I)


VHDL permite no slo modelar no slo el hardware sino tambin realizar un
banco de pruebas (test bench) para aplicar estmulos al diseo a fin de
analizar los resultados comparar los mismos de dos simulaciones
diferentes.
VHDL es entonces, adems de un lenguaje de descripcin de hardware, un
lenguaje para la definicin de estmulos a los modelos descritos en el mismo
entorno de diseo.
El comportamiento del componente bajo el estmulo definido en el test
bench puede verse en una pantalla del simulador que se emplee o puede
verificarse comparando con el comportamiento esperado usando
instrucciones a tal fin en el mismo test bench, o tambin puede guardarse
los datos resultado en archivos
En el test bench, adems de los datos de estmulo para el circuito, se pueden
generar los relojes que sean precisos y las inicializaciones correspondientes

TEMA 2.2 SENTENCIAS Y MODELOS

GENERACIN DE ESTMULOS EN VHDL (II)


Ejemplo:
entity LATCHD is
port (D, L: in BIT; Q, QN: out BIT );
end LATCHD;
architecture SECUENCIAL of LATCHD is
begin
process (L, D)
begin
if L = '1' and D = '0' then
Q <= '0' after 2 NS;
QN <= '1' after 3 NS;
elsif L = '1' and D = '1' then
Q <= '1' after 2 NS;
QN <= '0' after 3 NS;
end if;
end process;
end SECUENCIAL;

configuration CONF3 of LATCHD is


for SECUENCIAL
end for;
end CONF3;

TEMA 2.2 SENTENCIAS Y MODELOS

GENERACIN DE ESTMULOS EN VHDL (III)


Ejemplo:
entity TB is end TB;
architecture MIXTA of TB is
component LD
port ( D, L: in BIT; Q, QN: out BIT );
end component;
for DUT: LD use entity WORK.LATCHD(SECUENCIAL);
-- alternativa: for DUT: LD use configuration WORK.CONF3;
signal D, L, Q, QN: BIT;
begin
DUT: LD port map ( D, L, Q, QN );
ESTIMULOS: process
begin
L <= '1'; D <= '1';
wait for 10 NS; D <= '0';
wait for 10 NS; D <= '1';
wait for 10 NS; L <= '0';
wait for 10 NS; D <= '0';
wait for 10 NS; D <= '1';
wait;
end process ESTIMULOS;
end MIXTA;

TEMA 2.2 SENTENCIAS Y MODELOS

GENRICOS EN VHDL (I)


Los Genericos permiten especificar modelos parametrizados de
componentes. Dicha parametrizacin permite particularizar la estructura y
comportamiento de dichos componentes.
Visible para todas las arquitecturas asociadas a la entidad.
Sintaxis:
entity identificador is
[genricos]
[puertos]
[declaraciones]
[begin sentencias]
end [entity] [identificador];
component nombre_componente is
[etiqueta_referencia:] nombre_componente
[generic (lista_genricos);]
[generic map (lista_asociacin);]
[port (lista_puertos);]
[port map (lista_asociacin)];
end component [nombre_componente];

TEMA 2.2 SENTENCIAS Y MODELOS

GENRICOS EN VHDL (II)


Ejemplo:
--PISO(parallel in serial out)
entity piso is
generic ( width : integer := 7 );
--valor por defecto es 7
port ( clk : in std_logic;
load : in std_logic;
in1 : in std_logic_vector(width downto 0);
out1 : out std_logic);
end piso;
architecture Behavioral of piso is
signal temp: std_logic_vector (width downto 0) := (others => '0'); --inicializacion
begin
process(clk)
begin
if (load = 1') then -- load the register
temp <= in1;
elsif (clk'event and clk = '1') then Desplaza el registro y saca un bit.
out1 <= temp(width);
temp(width downto 1) <= temp(width-1 downto 0);
end if;
end process;
end Behavioral;

TEMA 2.2 SENTENCIAS Y MODELOS

GENRICOS EN VHDL (III)


Ejemplo:
entity test is
...
end test;
architecture behavior of test is
component piso
generic ( width : integer := 7 );
port ( clk : in std_logic;
load : in std_logic;
in1 : in std_logic_vector(width downto 0);
out1 : out std_logic);
end component;
--declaracion de seales
signal in1 : std_logic_vector(7 downto 0):="10000110";
signal in2 : std_logic_vector(3 downto 0):="1001";
signal load1,load2 : std_logic :='0';
begin
--ejemplos de paso de valores.
piso1 : piso generic map (width => 7) port map(clk,load1,in1,o1);
piso2 : piso generic map (width => 3) port map(clk,load2,in2,o2);
end behavior;

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (I)


Ejemplo 1: Contador BCD con carga asncrona
library IEEE;
else
use IEEE.STD_LOGIC_1164.ALL;
cuenta:= cuenta+1;
use IEEE.NUMERIC_STD.ALL;
end if;
entity cnt2 is
end if;
Port ( clk, ld : in std_logic;
end process;
din : in std_logic_vector(3 downto 0));
end arch
salida : out std_logic_vector(3 downto 0));
end cnt2;
architecture arch of cnt2 is
signal cuenta:unsigned(3 downto 0);
begin
salida <= std_logic_vector(cuenta);
process (clk, ld, din)
begin
if (ld='1') then
cuenta<= unsigned(din);
elsif (clk'event and clk='1') then
if cuenta=9 then
cuenta<= (others=> '0');

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (II)


Ejemplo 2: Multiplexor
library IEEE;
use IEEE.std_logic_1164.all;
entity mux4a1 is
port (S: in STD_LOGIC_VECTOR (2 downto 0);
-- Entradas de seleccin
A, B, C, D: in STD_LOGIC_VECTOR (1 to 18);
-- Data bus inputs
Y: out STD_LOGIC_VECTOR (1 to 18)
-- Data bus output
);
end mux4a1;
architecture mux4a1p of mux4a1 is
begin
process(S, A, B, C, D)

variable i: INTEGER;
begin
case S is
-- completar
end case;
end process;
end mux4a1p;

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (II)


Ejemplo 2: Multiplexor
variable i: INTEGER;
begin
case S is
entity mux4a1 is
when "000" | 100 => Y <= A;
port (S: in STD_LOGIC_VECTOR (2 downto 0);
when "001" | "101" => Y <= B;
-- Entradas de seleccin
A, B, C, D: in STD_LOGIC_VECTOR (1 to 18); when "010" | "110" => Y <= C;
when "011" | 111" => Y <= D;
-- Data bus inputs
when others => Y <= (others => 'U');
Y: out STD_LOGIC_VECTOR (1 to 18)
-- 18-bit vector of 'U'
-- Data bus output
end case;
);
end process;
end mux4a1;
end mux4a1p;
architecture mux4a1p of mux4a1 is
begin
process(S, A, B, C, D)
library IEEE;
use IEEE.std_logic_1164.all;

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (III)


Ejemplo 3: Multiplexor (otra forma)
library IEEE;
use IEEE.std_logic_1164.all;
entity mux2to1 is
port (a : in std_logic_vector(1 downto 0);
sel : in std_logic; muxed : out std_logic);
end mux2to1;
architecture rtl of mux2to1 is
begin
muxed <= a(1) when sel = '1' else a(0);
end rtl;
entity mux4to1 is
port (input : in std_logic_vector(3 downto 0);
sel : in std_logic_vector(1 downto 0);
muxed : out std_logic);
end mux4to1;
architecture structural of mux4to1 is
signal muxed_mid : std_logic_vector(1 downto 0);
component mux2to1
port (a : in std_logic_vector(1 downto 0);

sel : in std_logic; muxed : out std_logic);


end component;
Begin
-- completar
end structure;

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (III)


Ejemplo 3: Multiplexor (otra forma)
sel : in std_logic; muxed : out std_logic);
end component;
begin
entity mux2to1 is
mux2to1_1_0: mux2to1
port (a : in std_logic_vector(1 downto 0);
port map (
sel : in std_logic; muxed : out std_logic);
a => input(1 downto 0),
end mux2to1;
sel => sel(0),
architecture rtl of mux2to1 is
muxed => muxed_mid(0));
begin
mux2to1_3_2: mux2to1
muxed <= a(1) when sel = '1' else a(0);
port map (
end rtl;
a => input(3 downto 2),
sel => sel(0),
entity mux4to1 is
muxed => muxed_mid(1));
port (input : in std_logic_vector(3 downto 0);
mux2to1_final: mux2to1
sel : in std_logic_vector(1 downto 0);
Port map (
muxed : out std_logic);
a => muxed_mid,
end mux4to1;
sel => sel(1),
architecture structural of mux4to1 is
muxed => muxed);
signal muxed_mid : std_logic_vector(1 downto 0);
end structure;
component mux2to1
port (a : in std_logic_vector(1 downto 0);
library IEEE;
use IEEE.std_logic_1164.all;

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (IV)


Ejemplo 4: Decodificador de direcciones
library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.unsigned.ALL;
ENTITY deco_direcciones IS
GENERIC (
N: NATURAL := 3); --nmero de bits de direcc.
PORT (
address: IN STD_LOGIC_VECTOR(N-1 DOWNTO 0);
ena: IN STD_LOGIC;
word_line: OUT STD_LOGIC_VECTOR(2**N-1 DOWNTO 0));
END deco_direcciones;
ARCHITECTURE decoder OF deco_direcciones IS
SIGNAL addr: NATURAL RANGE 0 TO 2**N-1;
BEGIN
addr <= conv_integer(address);
gen: FOR i IN word_lineRANGE GENERATE
word_line (i) <=1 WHEN i=addr AND ena=1 ELSE 0;
END GENERATE;
END decoder;

TEMA 2.2 SENTENCIAS Y MODELOS

EJEMPLOS EN VHDL (V)


Ejemplo 5: Serial In Parallel Out (SIPO)
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
entity SerinParout is
port(
CLKs : in std_logic;
enable: in std_logic;
listo : out std_logic;
RST : in std_logic;
Serial: in std_logic;
Parallel : out std_logic_vector(7 downto 0));
end SerinParout;
--completar

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (I)


VHDL permite modelar fcilmente Mquinas de Estado Finito (MEF)
Entradas: datos, reset y clk
La generacin de las salidas puede depender de:
-El estado actual y las entradas actuales (MEALY).
-Slamente el estado actual (MOORE).

OUT
INP

EA LC

ES
LC

INP
LC

OUT

EA

ES
FF

LC

FF
MEALY

MOORE

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (II)


Consideraciones de diseo:
Declarar un tipo estado (enumerado) que recoja estados posibles:
type estado_MEF is (ESTADO_INICIAL, ESTADO1, ESTADO2, );
Declarar seales de tipo Estado_MEF:
signal estado actual, estado_siguiente: Estado MEF;
Un proceso controlado por el reloj y por reset decide cundo cambia el estado de
la mquina
Dependiendo del estado actual y de los valores de las entradas, el estado
siguiente se actualiza en el proceso correspondiente
El estado actual se actualiza en el flanco activo de reloj a partir del de estado
siguiente
Proveer una seal de reset que lleve la mquina al estado inicial:
STATUS: process (CLK, RST)
begin
if RST='1' then EA <= ESTADO_INICIAL;
..

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (III)


Formas de codificar MEF (Mealy y Moore).
Las distintas formas se estructuran en torno a la manera (procesos) de actualizar las
salidas, el estado actual y el estado siguiente:
Empleando un slo proceso
Empleando dos procesos
Empleando tres procesos
Al Sintetizar, cada forma conduce a un circuito con la misma funcionalidad, pero
caractersticas y prestaciones diferentes.

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (IV)


Mquina de estado con un solo proceso.
Existe un nico proceso que actualiza el estado actual y las salidas.
No se hace uso del estado siguiente
Ejemplo (Mealy):
entity TEST is port (X,CLK, RESET: in
STD_LOGIC; Z:out STD_LOGIC); end;

S0
X=1/Z=0

S1
X=1/Z=0

S2
X=1/Z=0
X=1/Z=1

S3

architecture F2 of TEST is
type ESTADO is (S0,S1,S2,S3);
signal EA: ESTADO;
Begin
UNICO: process
begin
wait until CLK'EVENT and CLK='1';
if RESET=1 then EA<=S0; Z<='0';
else
if X='0' then Z<='0';
else
case EA is
when S0 => EA <= S1; Z <= '0';
when S1 => EA <= S2; Z <= '0';
when S2 => EA <= S3; Z <= '0';
when S3 => EA <= S0; Z <= '1';
end case;
end if;
end if;
end process;
end F2;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (V)


Mquina de estado con dos procesos.
Crear un proceso para la actualizacin e inicializacin del estado actual.
Definir un proceso para la generacin del estado siguiente.
Ejemplo (Mealy): entity TEST is port (X,CLK, RESET: in STD_LOGIC; Z:out STD_LOGIC); end;

S0
X=1/Z=0

S1
X=1/Z=0

S2
X=1/Z=0
X=1/Z=1

S3

architecture F1 of TEST is
type ESTADO is (S0,S1,S2,S3);
signal ES, EA: ESTADO;
Begin
SYNCH: process
begin
wait until CLK'EVENT and CLK='1';
if RESET=1 then EA <= S0; else EA <= ES; end if;
end process;
COMB: process (EA, X)
begin
case EA is
when S0 => if X='1' then ES <= S1; else ES <= S0; end if; Z <= '0';
when S1 => if X='1' then ES <= S2; else ES <= S1; end if; Z <= '0';
when S2 => if X='1' then ES <= S3; else ES <= S2; end if; Z <= '0';
when S3 => if X='1' then ES <= S0; Z <= '1'; else ES <= S3; Z <= '0'; end if;
end case;
end process;
end F1;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (VI)


Mquina de estado con tres procesos.
Procesos para Estado_siguiente, Estado_actual y salidas .
Ejemplo (Mealy):
when zero=>
entity edge_detector2 is
port(clk, reset: in std_logic; strobe: in std_logic; p2: out std_logic);
end edge_detector2;
architecture mealy_arch of edge_detector2 is
type state_type is (zero, one);
signal state_reg, state_next: state_type;
begin
process(clk,reset) Proceso de Estado_actual
begin
if (reset='1') then state_reg <= zero;
elsif (clk'event and clk='1') then state_reg <= state_next;
end if;
end process;
process(state_reg,strobe) Proceso de Estado_siguiente
begin
case state_reg is

if strobe= '1' then


state_next <= one;
else
state_next <= zero;
end if;
when one =>
if strobe= '1' then
state_next <= one;
else
state_next <= zero;
end if;
end case;
end process;
-- Proceso de salidas
p2 <= '1' when
(state_reg=zero) and
(strobe='1') else '0';
end mealy_arch;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (VII)


Mquina de estado con tres procesos. Ejemplo (Moore):
entity edge_detector1 is
port(clk, reset: in std_logic; strobe: in std_logic; p1: out std_logic);
end edge_detector1;
architecture moore_arch of edge_detector1 is
type state_type is (zero, edge, one);
signal state_reg, state_next: state_type;
begin
process(clk, reset)
begin
if (reset='1') then state_reg <= zero;
elsif (clk'event and clk='1') then state_reg <= state_next;
end if;
end process;
process(state_reg,strobe) Proceso de Estado_siguiente
begin
case state_reg is
when zero=>
if strobe= '1' then state_next <= edge;
else
state_next <= zero;
end if;

when edge =>


if strobe= '1' then
state_next <= one;
else
state_next <= zero;
end if;
when one =>
if strobe= '1' then
state_next <= one;
else
state_next <= zero;
end if;
end case;
end process;
-- Proceso de salidas
p1 <= '1' when
state_reg=edge else '0';
end moore_arch;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (VIII)


Ejemplo Mquina de refrescos(I):
entity DRINK_STATE_VHDL is
port(NICKEL_IN, DIME_IN, QUARTER_IN, RESET:
BOOLEAN; CLK: BIT;
NICKEL_OUT, DIME_OUT, DISPENSE: out
BOOLEAN);
end;
architecture BEHAVIOR of DRINK_STATE_VHDL is
type STATE_TYPE is (IDLE, FIVE, TEN, FIFTEEN,
TWENTY, TWENTY_FIVE, THIRTY, OWE_DIME);
signal CURRENT_STATE, NEXT_STATE: STATE_TYPE;
begin
process(NICKEL_IN, DIME_IN, QUARTER_IN,
CURRENT_STATE, RESET, CLK)
begin
Default assignments
NEXT_STATE <= CURRENT_STATE;
NICKEL_OUT <= FALSE;
DIME_OUT <= FALSE;

DISPENSE <= FALSE;


Synchronous reset
if(RESET) then
NEXT_STATE <= IDLE;
else
State transitions and output logic
case CURRENT_STATE is
when IDLE =>
if(NICKEL_IN) then
NEXT_STATE <= FIVE;
elsif(DIME_IN) then
NEXT_STATE <= TEN;
elsif(QUARTER_IN) then
NEXT_STATE <= TWENTY_FIVE;
end if;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (VIII)


Ejemplo Mquina de refrescos(II):
when FIVE =>
if(NICKEL_IN) then
NEXT_STATE <= TEN;
elsif(DIME_IN) then
NEXT_STATE <= FIFTEEN;
elsif(QUARTER_IN) then
NEXT_STATE <= THIRTY;
end if;
when TEN =>
--completar
when FIFTEEN =>
if(NICKEL_IN) then
NEXT_STATE <= TWENTY;
elsif(DIME_IN) then
NEXT_STATE <= TWENTY_FIVE;

elsif(QUARTER_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
NICKEL_OUT <= TRUE;
end if;
when TWENTY =>
if(NICKEL_IN) then
NEXT_STATE <= TWENTY_FIVE;
elsif(DIME_IN) then
NEXT_STATE <= THIRTY;
elsif(QUARTER_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
DIME_OUT <= TRUE;
end if;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (VIII)


Ejemplo Mquina de refrescos(II):
when FIVE =>
if(NICKEL_IN) then
NEXT_STATE <= TEN;
elsif(DIME_IN) then
NEXT_STATE <= FIFTEEN;
elsif(QUARTER_IN) then
NEXT_STATE <= THIRTY;
end if;
when TEN =>
if(NICKEL_IN) then
NEXT_STATE <= FIFTEEN;
elsif(DIME_IN) then
NEXT_STATE <= TWENTY;
elsif(QUARTER_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
end if;
when FIFTEEN =>

if(NICKEL_IN) then
NEXT_STATE <= TWENTY;
elsif(DIME_IN) then
NEXT_STATE <= TWENTY_FIVE;
elsif(QUARTER_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
NICKEL_OUT <= TRUE;
end if;
when TWENTY =>
if(NICKEL_IN) then
NEXT_STATE <= TWENTY_FIVE;
elsif(DIME_IN) then
NEXT_STATE <= THIRTY;
elsif(QUARTER_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
DIME_OUT <= TRUE;
end if;

TEMA 2.2 SENTENCIAS Y MODELOS

DISEO DE MQUINAS DE ESTADOS EN VHDL (VIII)


Ejemplo Mquina de refrescos(III):
when TWENTY_FIVE =>
if(NICKEL_IN) then
NEXT_STATE <= THIRTY;
elsif(DIME_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
elsif(QUARTER_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
DIME_OUT <= TRUE;
NICKEL_OUT <= TRUE;
end if;
when THIRTY =>
if(NICKEL_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;
elsif(DIME_IN) then
NEXT_STATE <= IDLE;
DISPENSE <= TRUE;

NICKEL_OUT <= TRUE;


elsif(QUARTER_IN) then
NEXT_STATE <= OWE_DIME;
DISPENSE <= TRUE;
DIME_OUT <= TRUE;
end if;
when OWE_DIME =>
NEXT_STATE <= IDLE;
DIME_OUT <= TRUE;
end case;
end if;
end process;
Synchronize state value with clock.
This causes it to be stored in flip flops
process
begin
wait until CLKevent and CLK = 1;
CURRENT_STATE <= NEXT_STATE;
end process;
end BEHAVIOR;

Potrebbero piacerti anche