0
0
Verilogprogramming~5 mins

Up-down counter with direction control in Verilog

Choose your learning style9 modes available
Introduction

An up-down counter counts numbers up or down based on a control signal. It helps track values that can increase or decrease.

When you want to count events that can go forward or backward, like steps taken or items added/removed.
In digital clocks to count seconds up or down.
To control volume or brightness levels that can increase or decrease.
In simple games to track score changes up or down.
Syntax
Verilog
module up_down_counter(
    input clk,
    input reset,
    input direction, // 1 for up, 0 for down
    output reg [3:0] count
);

always @(posedge clk or posedge reset) begin
    if (reset) begin
        count <= 0;
    end else if (direction) begin
        count <= count + 1;
    end else begin
        count <= count - 1;
    end
end

endmodule

The direction input controls counting up (1) or down (0).

Use posedge clk to update count on clock's rising edge.

Examples
This line increases the count by 1.
Verilog
count <= count + 1; // count up
This line decreases the count by 1.
Verilog
count <= count - 1; // count down
Reset sets the count back to zero.
Verilog
if (reset) count <= 0;
Sample Program

This program counts up for some time, then counts down. The testbench shows how the counter changes.

Verilog
module up_down_counter(
    input clk,
    input reset,
    input direction,
    output reg [3:0] count
);

always @(posedge clk or posedge reset) begin
    if (reset) begin
        count <= 0;
    end else if (direction) begin
        count <= count + 1;
    end else begin
        count <= count - 1;
    end
end

endmodule

// Testbench
module testbench();
    reg clk = 0;
    reg reset;
    reg direction;
    wire [3:0] count;

    up_down_counter uut(clk, reset, direction, count);

    always #5 clk = ~clk; // Clock toggles every 5 time units

    initial begin
        $monitor($time, " count = %d", count);
        reset = 1; direction = 1;
        #10 reset = 0;
        // Count up for 50 time units
        #50 direction = 0; // Change direction to down
        // Count down for 50 time units
        #50 $finish;
    end
endmodule
OutputSuccess
Important Notes

Make sure the counter width (here 4 bits) fits the range you need.

When counting down below zero, the counter wraps around (underflows).

Summary

An up-down counter changes its count based on a direction signal.

Use reset to start counting from zero.

Counting up adds 1; counting down subtracts 1 on each clock pulse.