Bootstrap

Grey encoder and decoder

Author: Rui
Reference from the website and wikipedia

Something to mention:

1.$display always to display the last sampled value,may cause some mismatch in the screen output

2.parameterized module design help to scaling 

Grey encoder

//  grey encoder, from binary input to grey output
//  algorithm:
//  from rightmost, x[i] xor x[i+1], keep the leftmost bit module grey_encoder#( parameter WIDTH =  4)

    (input [WIDTH - 1 : 0] bin,
    output [WIDTH - 1 : 0]grey);
wire [WIDTH-2 : 0] temp;

assign temp =  bin[WIDTH -1:1];
assign grey = {bin[WIDTH-1], temp ^ bin[WIDTH -2 :0]};
endmodule

 

Grey decoder 

// algorithm
// keep the leftmost bit
// b[n] = g[n], b[i] = b[i+1] xor g[i] i:0~n-2
// pretty simple to understand, use xor 0 to keep the bit, xor 1 to invert bit
module grey_decoder#( parameter WIDTH= 4)
    ( input [WIDTH- 1: 0] grey,
     output  reg [WIDTH- 1: 0] bin);
integer i;
always@(grey)  begin
    bin[WIDTH- 1] = grey[WIDTH- 1];
     for (i=(WIDTH- 2); i>= 0; i=i- 1)
        bin[i] = bin[i+ 1] ^ grey[i];
end
endmodule

 

 

Testbench

//  testbench for grey encoder
//  Author Rui Chen

` include  " grey.v "
module grey_top;
parameter WIDTH =  4;
reg [WIDTH- 1 :  0] bin, grey2;
wire [WIDTH- 1 :  0] grey, bin2;

grey_encoder #(.WIDTH(WIDTH)) encoder (.bin(bin), .grey(grey));
grey_decoder #(.WIDTH(WIDTH)) decoder (.grey(grey2), .bin(bin2));

always@(grey) grey2 = grey;

initial  begin
    $display( " debug output ");
     repeat( 10begin
    # 3 bin = $random;
    $display( " encoder part ");
    $display( " binary input: %b, grey output: %b ", bin, grey);
    $display( " decoder part ");
    $display( " grey input: %b, binary output: %b ", grey2, bin2);
     end
    # 3 $finish;
end

initial  begin
    $dumpfile( " grey.vcd ");
    $dumpvars;
end
endmodule


 

Simulation result

 

转载于:https://www.cnblogs.com/chenrui/archive/2012/04/05/2432711.html

;