Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Gray Counter

Verilog Counters

Example of a simple parameterizable gray counter

Open in IDE
Related tutorial:
design.v
module gray_ctr
  # (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
testbench.v
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
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.