4-Bit Down Counter Verilog Code and Test Bench
Advertisement
This document provides Verilog code for a 4-bit down counter and its corresponding test bench.
4-Bit Down Counter Verilog Code
Here’s the Verilog code for a 4-bit down counter.
`define TICK #2
module downCntr(clk, reset, Q);
  input clk, reset;
  output [3:0] Q;
  reg [3:0] Q;
  // Behavioral Code for a Down Counter
  always @ (posedge clk)
  begin
    if (~reset)
    begin
      Q <= Q-1;
    end
  end
  always @ (posedge reset)
  begin
    Q <= 4'b0000;
  end
endmodule
Explanation:
- 
“define TICK #2 : This line defines a macro namedTICK`, which is used to represent a time delay (in this case, 2 time units). This is useful for controlling simulation timing.
- 
module downCntr(clk, reset, Q);: This declares a module nameddownCntrwith inputsclk(clock) andreset, and an outputQ(the 4-bit counter value).
- 
input clk, reset;: Declaresclkandresetas inputs.
- 
output [3:0] Q;: DeclaresQas a 4-bit output.
- 
reg [3:0] Q;: DeclaresQas a 4-bit register, as it will be assigned a value within thealwaysblock.
- 
always @ (posedge clk): This block is triggered on the positive edge of the clock.
- 
if (~reset): Checks if the reset signal is low (active low reset).
- 
Q <= Q-1;: If the reset is not asserted, the counter decrements its value by 1 on each clock cycle.
- 
always @ (posedge reset): This block is triggered on the positive edge of the reset signal.
- 
Q <= 4'b0000;: When the reset signal is asserted (high), the counter is reset to 0.
4-Bit Down Counter Test Bench Code
The following Verilog code provides the test bench for the 4-bit down counter.
module main;
  reg clk, reset;
  wire [3:0] Q;
  downCntr dnCntr1(clk, reset, Q);
  initial
  begin
    forever
    begin
      clk <= 0; #5 clk <= 1; #5 clk <= 0;
    end
  end
  initial
  begin
    reset = 1; #12 reset = 0; #170 reset = 1; #12 reset = 0;
  end
endmodule
Explanation:
- 
module main;: Defines the test bench module namedmain.
- 
reg clk, reset;: Declaresclkandresetas registers, as they will be driven by the test bench.
- 
wire [3:0] Q;: DeclaresQas a wire, connecting it to the output of thedownCntrmodule.
- 
downCntr dnCntr1(clk, reset, Q);: Instantiates thedownCntrmodule, connecting its inputs and outputs.
- 
initial begin ... end: These blocks define the initial behavior of the clock and reset signals.
- 
The first initialblock generates a clock signal with a period of 10 time units (5 for low and 5 for high).
- 
The second initialblock applies a reset signal. It starts asserted, de-asserts after 12 time units, re-asserts after 170 time units, and de-asserts again after another 12 time units. This allows you to observe the counter’s behavior with and without reset conditions.
Advertisement
 RF
RF 
  
  
  
  
  
  
 