verilog example
counter_4bit.v
module counter_4bit ( input wire clk, // Clock input input wire rst_n, // Active-low reset input wire en, // Enable signal output reg [3:0] q // 4-bit counter output); // Counter logic always @(posedge clk or negedge rst_n) begin if (!rst_n) q <= 4\'b0000; // Reset counter else if (en) q <= q + 1\'b1; // Increment counter if enabled endendmodule
counter_4bit_tb.v
`timescale 1ns / 1psmodule counter_4bit_tb; reg clk; reg rst_n; reg en; wire [3:0] q; // Instantiate the counter counter_4bit uut ( .clk(clk), .rst_n(rst_n), .en(en), .q(q) ); // Generate clock: toggles every 5ns (10ns period = 100MHz) always #5 clk = ~clk; initial begin $monitor(\"At time %0t: clk=%b rst_n=%b en=%b q=%b\", $time, clk, rst_n, en, q); // Dump waveform data// $dumpfile(\"counter.vcd\"); // Name of the waveform file // $dumpvars(0, counter_4bit_tb); // Dump all signals in this module // Initialize signals clk = 0; rst_n = 0; en = 0; // Reset pulse #10 rst_n = 1; // Enable counting #10 en = 1; // Run for 100ns #100; // Stop simulation $stop; endendmodule
run
iverilog -o counter_sim counter_4bit.v counter_4bit_tb.vvvp counter_sim