Introduction
An up-down counter counts numbers up or down based on a control signal. It helps track values that can increase or decrease.
An up-down counter counts numbers up or down based on a control signal. It helps track values that can increase or decrease.
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
endmoduleThe direction input controls counting up (1) or down (0).
Use posedge clk to update count on clock's rising edge.
count <= count + 1; // count upcount <= count - 1; // count downif (reset) count <= 0;
This program counts up for some time, then counts down. The testbench shows how the counter changes.
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
endmoduleMake sure the counter width (here 4 bits) fits the range you need.
When counting down below zero, the counter wraps around (underflows).
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.
reg [2:0] count = 3'b000; always @(posedge clk) begin if(reset) count <= 3'b000; else if(dir) count <= count + 1; else count <= count - 1; end
reset=0, dir=1, and the clock pulses 5 times starting from 0, what is the value of count after 5 pulses?reg [3:0] count; always @(posedge clk) begin if(reset) count = 0; else if(dir) count <= count + 1; else count <= count - 1; end
Pass the test and this pattern moves unknown