Pages

Saturday, October 28, 2017

4 bit Binary to Gray code and Gray code to Binary converter in Verilog


UPDATE : A GENERIC GRAY CODE CONVERTER IS AVAILABLE HERE



Gray codes are non-weighted codes, where two successive values differ only on one bit. Through this post, I want to share two simple gate level Verilog codes for converting binary number to Gray and vice versa.

Logic circuit for 4 bit Binary to Gray code converter:


Logic circuit for 4 bit Gray code to Binary converter:


Verilog Code for Binary to Gray code conversion:

module bin2gray
        (input [3:0] bin, //binary input
         output [3:0] G //gray code output
        );

//xor gates.
assign G[3] = bin[3];
assign G[2] = bin[3] ^ bin[2];
assign G[1] = bin[2] ^ bin[1];
assign G[0] = bin[1] ^ bin[0];

endmodule

Verilog Code for Gray code to Binary conversion:

module gray2bin
        (input [3:0] G, //gray code output
         output [3:0] bin   //binary input
        );

assign bin[3] = G[3];
assign bin[2] = G[3] ^ G[2];
assign bin[1] = G[3] ^ G[2] ^ G[1];
assign bin[0] = G[3] ^ G[2] ^ G[1] ^ G[0];

endmodule

Single Testbench for both the designs:

module tb();

   reg [3:0] bin;
    wire [3:0] G,bin_out;
    
    // instantiate the unit under test's (uut)
   bin2gray uut1(bin,G);
   gray2bin uut2(G,bin_out);
    
   // stimulus
   always
   begin        
      bin <= 0; #10;
        bin <= 1;   #10;
        bin <= 2;   #10;
        bin <= 3;   #10;
        bin <= 4;   #10;
        bin <= 5;   #10;
        bin <= 6;   #10;
        bin <= 7;   #10;
        bin <= 8;   #10;
        bin <= 9;   #10;
        bin <= 10;  #10;
        bin <= 11;  #10;
        bin <= 12;  #10;
        bin <= 13;  #10;
        bin <= 14;  #10;
        bin <= 15;  #10;
        #100;   
      $stop;
   end

endmodule

Simulation Waveform:

The code was simulated using Xilinx ISE 14.6 tool. The following waveform verifies the correctness of both the designs. The output of binary to gray module is connected as input of gray to binary converter. As you can see the bin and bin_out signals are the same. This verifies that the codes are working well.


Do you notice a pattern in how the output bits are calculated. What do you think of of an n-bit converter? For learning purposes, try implementing an n-bit version of the above designs.

I have also implemented the exact logic circuit in VHDL. If interested visit it in my VHDLblog, 4 bit VHDL code for gray code to binary and vice versa.