Few years back I had written a 4 bit converter for conversion between Gray and Binary codes. After receiving much positive response I decided to write a generic version of the same.
Let me share the codes...
Binary to Gray Code Converter:
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
entity bin2gray is
generic(N : integer := 4);
port( bin : in std_logic_vector(N-1 downto 0); --binary input
G : out std_logic_vector(N-1 downto 0) --gray code output
);
end bin2gray;
architecture gate_level of bin2gray is
begin
G(N-1) <= bin(N-1);
--generate xor gates.
xor_gates : for i in N-2 downto 0 generate
G(i) <= bin(i+1) xor bin(i);
end generate;
end;
Gray Code to Binary Converter:
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
entity gray2bin is
generic(N : integer := 4);
port( G : in std_logic_vector(N-1 downto 0); --gray code input
bin : out std_logic_vector(N-1 downto 0) --binary output
);
end gray2bin;
architecture gate_level of gray2bin is
signal temp : std_logic_vector(N-1 downto 0);
begin
temp(N-1) <= G(N-1);
--generate xor gates.
xor_gates : for i in N-2 downto 0 generate
temp(i) <= temp(i+1) xor G(i);
end generate;
bin <= temp;
end;
Testbench:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity tb is
end tb;
architecture behavior of tb is
-- component declaration for the unit under test's (uut)
component bin2gray is
generic(N : integer := 4);
port( bin : in std_logic_vector(N-1 downto 0); --binary input
G : out std_logic_vector(N-1 downto 0) --gray code output
);
end component;
component gray2bin is
generic(N : integer := 4);
port( G : in std_logic_vector(N-1 downto 0); --gray code input
bin : out std_logic_vector(N-1 downto 0) --binary output
);
end component;
constant N : integer := 16; --Change this to control the number of bits in the input/output.
signal bin,g,bin_out : std_logic_vector(N-1 downto 0) := (others => '0');
signal error : integer := 0;
begin
-- Both the converters are connected back to back to see the binary input going to the
--first entity is the same as the output coming out of the second entity.
uut1: bin2gray generic map (N => N) port map (
bin => bin,
g => g
);
uut2: gray2bin generic map (N => N) port map (
g => g,
bin => bin_out
);
-- stimulus process
--this tests for all the input combinations.
stim_proc: process
begin
for i in 0 to 2**N-1 loop --loop through all the available inputs
bin <= std_logic_vector(to_unsigned(i,N)); --convert integer to std_logic_vector.
wait for 5 ns;
--Count the number of errors. Should be zero at the end of simulation.
if(bin /= bin_out) then
error <= error + 1;
end if;
wait for 5 ns;
end loop;
wait;
end process;
end;
The codes were tested using Modelsim 10.4a version. Simply change the value of the constant 'N' in the testbench to test for different sized converters.
No comments:
Post a Comment