type your search

Tuesday, January 10, 2012

A 3 bit Magnitude Comparator using logic gates

  In this post I have shared a 3 bit comparator which is designed using basic logic gates such as XNOR, OR, AND etc. The code was tested using  a testbench code which tested the design for all the 81 combinations of inputs.

See the code below:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity comparator is
port( a,b : in unsigned(2 downto 0);  --3 bit numbers to be compared
        a_eq_b : out std_logic;  --a equals b
        a_le_b : out std_logic;  --a less than b
        a_gt_b : out std_logic   --a greater than b
      );    
end comparator;

architecture gate_level of comparator is

signal temp1,temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9 : std_logic := '0';

BEGIN

temp1 <= not(a(2) xor b(2));  --XNOR gate with 2 inputs.
temp2 <= not(a(1) xor b(1));  --XNOR gate with 2 inputs.
temp3 <= not(a(0) xor b(0));  --XNOR gate with 2 inputs.
temp4 <= (not a(2)) and b(2);
temp5 <= (not a(1)) and b(1);
temp6 <= (not a(0)) and b(0);
temp7 <= a(2) and (not b(2));
temp8 <= a(1) and (not b(1));
temp9 <= a(0) and (not b(0));

a_eq_b <= temp1 and temp2 and temp3;  -- for a equals b.
a_le_b <= temp4 or (temp1 and temp5) or (temp1 and temp2 and temp6); --for a less than b
a_gt_b <= temp7 or (temp1 and temp8) or (temp1 and temp2 and temp9); --for a greater than b

end gate_level;

The testbench code for testing the design is given below:

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;

ENTITY tb IS
END tb;

ARCHITECTURE behavior OF tb IS
   --Inputs
   signal a : unsigned(2 downto 0) := (others => '0');
   signal b : unsigned(2 downto 0) := (others => '0');
    --Outputs
   signal a_eq_b : std_logic;
   signal a_le_b : std_logic;
   signal a_gt_b : std_logic;

    signal i,j : integer;

BEGIN

    -- Instantiate the Unit Under Test (UUT)
   uut: entity work.comparator PORT MAP (
          a => a,
          b => b,
          a_eq_b => a_eq_b,
          a_le_b => a_le_b,
          a_gt_b => a_gt_b
        );

   -- Stimulus process
   stim_proc: process
   begin       
        for i in 0 to 8 loop
            for j in 0 to 8 loop
                a <= to_unsigned(i,3); --integer to unsigned type conversion
                b <= to_unsigned(j,3);
                wait for 10 ns;
            end loop;
        end loop;  
   end process;

END;
A part of the simulation waveform is given below:

Note:- For viewing the full results simulate the program yourself. The code was tested using Xilinx ISE 12.1 version. But it will work with almost all the compilers.The code is also synthesisable.

No comments:

Post a Comment