May 1, 2026

Verilog Code for 4-bit Up-Down Counter (With Explanation & Testbench) | #24

Welcome to another edition of our Verilog series! In this blog post, we’ll explore the implementation of an Up-Down Counter in Verilog. An up-down counter is a sequential circuit that can increment or decrement its value based on a control signal.

This type of counter is widely used in digital systems where flexible counting operations are required.

Below is the Verilog code for a 4-bit Up-Down Counter, implemented using a Behavioral Modeling approach:

๐Ÿ“Š Block Diagram

(Insert your up-down counter diagram here)

In this design, the direction of counting is controlled by an input signal.

module up_down_counter(
  input clk,
  input reset,
  input mode,   // mode = 1 → up, mode = 0 → down
  output reg [3:0] Q
);

always @(posedge clk or posedge reset)
begin
  if (reset)
    Q <= 4'b0000;
  else if (mode)
    Q <= Q + 1;
  else
    Q <= Q - 1;
end

endmodule

๐Ÿงช Testbench

module tb_top;
  reg clk, reset, mode;
  wire [3:0] Q;

  up_down_counter uut(clk, reset, mode, Q);

  initial begin
    clk = 0;
    forever #5 clk = ~clk;
  end

  initial begin
    $monitor("Time=%0t mode=%b Q=%b", $time, mode, Q);

    reset = 1; #10;
    reset = 0;

    mode = 1; #40; // Up counting
    mode = 0; #40; // Down counting

    #20 $finish;
  end
endmodule

Explanation:

  • The counter increments when mode = 1.
  • The counter decrements when mode = 0.
  • The reset signal initializes the counter to zero.
  • The output Q represents the current count value.
  • The counter operates synchronously with the clock signal.

Conclusion

This Verilog implementation of an Up-Down Counter demonstrates flexible counting behavior using a simple control signal. It is widely used in applications requiring bidirectional counting.

What’s Next?

Try implementing a Mod-N Counter to control the counting range. In the next post, we’ll explore more advanced counter designs.

Happy Coding! ๐Ÿš€

No comments:

Post a Comment

Explore Our Topics!

Check out the extensive list of topics we discuss:  Tech and AI Blogs Communication Protocols: -  USB   - RS232   -  Ethernet   -  AMBA Prot...