Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Bhagyasree K V

BRN 46

CODING TEST

1. Write Verilog RTL code and TB to generate N bit gray code counter.

1.RTL CODE

module gray_code

# (parameter N = 4)

( input clk,

input rstn,

output reg [N-1:0] out);

reg [N-1:0] q;

always @ (posedge clk) begin

if (!rstn) begin

q <= 0;

out <= 0;

end else begin

q <= q + 1;

`ifdef FOR_LOOP

for (int i = 0; i < N-1; i= i+1) begin

out[i] <= q[i+1] ^ q[i];

end

out[N-1] <= q[N-1];

`else

out <= {q[N-1], q[N-1:1] ^ q[N-2:0]};

`endif

end

end
endmodule

2.Test Bench

module tb;

parameter N = 4;

reg clk;

reg rstn;

wire [N-1:0] out;

gray_ctr u0 ( .clk(clk),

.rstn(rstn),

.out(out));

always #10 clk = ~clk;

initial begin

{clk, rstn} <= 0;

$monitor ("T=%0t rstn=%0b out=0x%0h", $time, rstn, out);

repeat(2) @ (posedge clk);

rstn <= 1;

repeat(20) @ (posedge clk);

$finish;

end

endmodule

You might also like