A 4-bit counter with a synchronous reset: the reset acts only at a clock edge, so it is just another input to the logic in front of the flip-flops. [3:0] declares 4 bits, numbered 3 down to 0. A number such as 4'd1 gives its width in bits, a base (d decimal, b binary) and its value; so 1'b0 is the 1-bit binary 0.
module counter4 (input clk, input rst, output reg [3:0] q);
always @(posedge clk) begin
if (rst) q <= 4'd0; // checked only at the edge
else q <= q + 4'd1; // wraps from 15 to 0
end
endmodule
A finite-state machine stores its state in flip-flops. At each edge the state takes the next state, which logic computes from the present state and the inputs. This two-state machine toggles when input x is 1 and holds when x is 0. One clocked block holds the state register, one always @(*) block the next-state logic, and an assign gives the output.
module fsm2 (input clk, input rst, input x, output z);
reg state, next_state; // state is 0 or 1
always @(posedge clk) // state register
if (rst) state <= 1'b0; else state <= next_state;
always @(*) // next-state logic
if (x) next_state = ~state; else next_state = state;
assign z = state; // output depends on state only
endmodule
TWO-STATE MACHINE NEXT STATE
S+=S⊕x,z=S
At each rising edge with rst=0 (rst=1 gives S+=0). S is the state bit (0 or 1), x the input, ⊕ is XOR: S flips when x=1 and stays when x=0. z is the output.
A testbench is a module, usually with no ports, that drives your design and runs only in simulation. It may use delays (#) and initial blocks, which describe time. Synthesis never reads it.
`timescale 1ns/1ps // # delays count in ns
module tb;
reg clk = 0, rst = 1; wire [3:0] q;
counter4 dut (.clk(clk), .rst(rst), .q(q)); // port clk to signal clk, and so on
always #5 clk = ~clk; // toggles every 5 ns: period 10 ns
initial begin // runs once, from time 0
$monitor("t=%0t q=%0d", $time, q); // %0t: time, %0d: q in decimal; prints when q changes
#12 rst = 0; // release reset between edges
#200 $finish; // stop the simulation
end
endmodule
CLOCK PERIOD OF THE COUNTER
Tclk≥tclk-q+tlogic,max+tsetup
Setup constraint of Chapter 4 with skew taken as zero. Tclk is the clock period, tclk-q the clock-to-Q delay, tsetup the setup time and tlogic,max the longest delay of the incrementer and reset gating between the counter's flip-flops. All times in ns.