Verilog Coding Tips and Tricks: Generic Verilog Code for Binary to Gray and Gray to Binary converter

Sunday, December 13, 2020

Generic Verilog Code for Binary to Gray and Gray to Binary converter

     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:



//Binary to Gray code Converter
//The 'parameter' keyword below is how we give the inputs/outputs a generic size.
module bin2gray #(parameter N = 4)
        ( input [N-1:0] bin,    //binary input
        output [N-1:0] G);      //Gray output

assign G[N-1] = bin[N-1];

//generate xor gates.
//the loop index need to be declared as 'genvar' and it can be done
//as you can see inside the 'for' loop.
//The instantiation is labelled as 'xor_gates_b2g'. 
//Always put a label when you generate instantiations.
//The 'generate' keyword need not be explicitly written.
for(genvar i=N-2;i>=0;i=i-1begin : xor_gates_b2g
    xor(G[i],bin[i+1],bin[i]);
end

endmodule


Gray Code to Binary Converter:



//Gray code to Binary Converter
module gray2bin #(parameter N = 4)
        ( input [N-1:0] G,    //Gray input
        output [N-1:0] bin);      //Binary output

assign bin[N-1] = G[N-1];

for(genvar i=N-2;i>=0;i=i-1begin : xor_gates_g2b
    xor(bin[i],G[i],bin[i+1]);
end

endmodule


Testbench:



//Testbench which connects both the converters back to back.
module tb;  //testbench module is always empty.

parameter N = 16;   //Change this to control the number of bits in the input/output.
reg [N-1:0] bin;
wire [N-1:0] G,bin_out;
reg [N:0] i;
integer error;  //this counts the number of errors during simulation.

    //Both the converters are connected back to back to see the binary input going to the
    //first module is the same as the output coming out of the second module.
    bin2gray #(.N(N)) uut1
        (
          .bin(bin),
          .G(G)
        );
 
    gray2bin #(.N(N)) uut2
        (
          .G(G),  
          .bin(bin_out)
        );
          
    initial 
    begin
        error = 0;  //initialize the error as zero.
        for(i=0;i<2**N;i=i+1begin     //loop through all the  available inputs 
            bin = i[N-1:0];
            #5;
            //Count the number of errors.It should be zero at the end of simulation.
            if(bin != bin_out)  
                error = error + 1;
            #5;
        end
        #10;
        $stop;  //All possible inputs are tested. So stop the simulation.
    end          

endmodule


    The codes were tested using Modelsim 10.4a version. Simply change the value of the parameter 'N' in the testbench to test for different sized converters.

A screenshot of the simulation waveform is shown below:





1 comment: