Friday, October 30, 2009

VHDL code for Counter

VHDL code for Counter

library IEEE;

use IEEE.std_logic_1164.all;

use IEEE.numeric_std.all; -- for the unsigned type
entity counter_example is

generic ( WIDTH : integer := 32);

port (

CLK, RESET, LOAD : in std_logic;

DATA : in unsigned(WIDTH-1 downto 0);

Q : out unsigned(WIDTH-1 downto 0));

end entity counter_example;
architecture counter_example_a of counter_example is

signal cnt : unsigned(WIDTH-1 downto 0);

begin

process(RESET, CLK)

begin

if RESET = '1' then

cnt <= (others => '0');

elsif rising_edge(CLK) then

if LOAD = '1' then

cnt <= DATA;

else

cnt <= cnt + 1;

end if;

end if;

end process;

Q <= cnt;

end architecture counter_example_a;

VHDL code for FlipFlops

VHDL code for FlipFlops

Some flip-flops also have Enable signals and asynchronous or synchronous Set and Reset signals:

-- template for asynchronous reset with clock enable:

process(CLK, RESET)

begin

if RESET = '1' then -- or '0' if RESET is active low...

Q <= '0';

elsif rising_edge(CLK) then

if Enable = '1' then -- or '0' if Enable is active low...

Q <= D;

end if;

end if;

end process;
-- template for synchronous reset with clock enable:

process(CLK)

begin

if rising_edge(CLK) then

if RESET = '1' then

Q <= '0';

elsif Enable = '1' then -- or '0' if Enable is active low...

Q <= D;

end if;

end if;

end process;

VHDL code for D-type flipflops

D-type flipflops

-- simplest DFF template (not recommended) 

Q <= D when rising_edge(CLK);
-- recommended DFF template:

process(CLK)

begin

-- use falling_edge(CLK) to sample at the falling edge instead

if rising_edge(CLK) then

Q <= D;

end if;

end process;
-- alternative DFF template:

process

begin

wait until rising_edge(CLK);

Q <= D;

end process;
-- alternative template:

process(CLK)

begin

if CLK = '1' and CLK'event --use rising edge, use "if CLK = '0' and CLK'event" instead for falling edge

Q <= D;

endif;

end process;

Latch Templates

Latch Templates

A transparent latch is basically one bit of memory which is updated when an enable signal is raised:

-- latch template 1:

Q <= D when Enable = '1' else Q;
-- latch template 2:

process(D,Enable)

begin

if Enable = '1' then

Q <= D;

end if;

end process;

A SR-latch uses a set and reset signal instead:

-- SR-latch template 1:

Q <= '1' when S = '1' else

'0' when R = '1' else Q;

-- SR-latch template 2:

process(S,R)

begin

if S = '1' then

Q <= '1';

elsif R = '1' then

Q <= '0';

end if;

end process;

Template 2 has an implicit "else Q <= Q;" which may be explicitly added if desired.

-- This one is a RS-latch (i.e. reset dominates)

process(S,R)

begin

if R = '1' then

Q <= '0';

elsif S = '1' then

Q <= '1';

end if;

end process;

Popular Posts