Saturday, 2 December 2017

VHDL Code For 3-bit Gray Code Counter

The state diagram for a 3-bit Gray Code Counter is shown:
Source: http://www.tankonyvtar.hu/hu/tartalom/tamop412A/2011-0041_digital_technics/ch03s04.html
VHDL Code:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use ieee.std_logic_unsigned.all;
entity gray_counter is
port(clk, reset: in std_logic;
dout: out std_logic_vector(2 downto 0));
end gray_counter;

architecture Behavioral of gray_counter is
signal temp: std_logic_vector(2 downto 0);
signal temp_gray: std_logic_vector(2 downto 0);
begin
process(clk, reset)
begin
if(reset='1') then temp<="000";
elsif(clk'event and clk='1') then
temp<= temp+1;
end if;
end process;
process(temp)
begin
temp_gray(2)<=temp(2);
temp_gray(1)<= temp(1) xor temp(2);
temp_gray(0)<= temp(1) xor temp(0);
end process;
dout<=temp_gray;
end Behavioral;

Testbench Code:

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
ENTITY graytb IS
END graytb;
 
ARCHITECTURE behavior OF graytb IS  
    -- Component Declaration for the Unit Under Test (UUT)
    COMPONENT gray_counter
    PORT(
         clk : IN  std_logic;
         reset : IN  std_logic;
         dout : OUT  std_logic_vector(2 downto 0)
        );
    END COMPONENT;

   --Inputs
   signal clk : std_logic := '0';
   signal reset : std_logic := '0';

  --Outputs
   signal dout : std_logic_vector(2 downto 0);

   -- Clock period definitions
   constant clk_period : time := 100 ns;
 
BEGIN
-- Instantiate the Unit Under Test (UUT)
   uut: gray_counter PORT MAP (
          clk => clk,
          reset => reset,
          dout => dout
        );

   -- Clock process definitions
   clk_process :process
   begin
clk <= '0';
wait for clk_period/2;
clk <= '1';
wait for clk_period/2;
   end process;
   -- Stimulus process
   stim_proc: process
   begin
      -- hold reset state for 100 ns.
reset<='1';
      wait for 100 ns;
reset<='0';
wait for 800 ns;
   end process;
END;

Waveform: