0
0
Verilogprogramming~5 mins

Why counters are fundamental in Verilog

Choose your learning style9 modes available
Introduction

Counters help us keep track of how many times something happens. They are like a tally in real life, counting events or steps automatically.

Counting how many clock pulses have passed in a digital circuit.
Measuring time intervals by counting clock cycles.
Creating delays or timed events in hardware.
Generating sequences or patterns that repeat after a certain count.
Controlling how many times a process runs before stopping.
Syntax
Verilog
module counter(
  input clk,
  input reset,
  output reg [3:0] count
);

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

endmodule

The always @(posedge clk or posedge reset) block runs on every rising edge of the clock or reset signal.

The counter resets to zero when reset is high, otherwise it increments by one each clock cycle.

Examples
This line increases the counter by one each time it runs.
Verilog
count <= count + 1;
This resets the counter to zero when the reset signal is active.
Verilog
if (reset) count <= 0;
This declares an 8-bit register to hold the count value.
Verilog
output reg [7:0] count;
Sample Program

This program defines a simple 4-bit counter that resets to zero and counts up on each clock pulse. The testbench simulates the clock and reset signals and prints the count value over time.

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

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

endmodule

// Testbench to simulate the counter
module testbench();
  reg clk = 0;
  reg reset = 0;
  wire [3:0] count;

  simple_counter uut(.clk(clk), .reset(reset), .count(count));

  // Clock generation
  always #5 clk = ~clk; // 10 time units period

  initial begin
    $monitor($time, " count = %d", count);
    reset = 1; #10;
    reset = 0;
    #100;
    $finish;
  end
endmodule
OutputSuccess
Important Notes

Counters are the building blocks for timers, frequency dividers, and many control circuits.

Make sure to handle reset properly to avoid unexpected counts.

Summary

Counters automatically track events or time by counting pulses.

They are essential for timing, sequencing, and control in digital circuits.

Resetting counters ensures they start counting from a known state.