Skip to content

Digital Logic: Introduction to Sequential Logic—Counters and Clock Dividers

Objectives

  • Master the use of always @(posedge clk or negedge rst_n).
  • Learn to design binary and modulo-N counters.
  • Learn to design a clock divider that converts a 100 MHz clock into a required lower-frequency signal.
  • Complete the 1 Hz LED blinking exercise and experience a circuit that changes by itself.

1. Understanding Clock Signals

The EGO1 development board has a 100 MHz crystal oscillator connected to FPGA pin P17. It continuously produces a square wave:

        ┌──┐  ┌──┐  ┌──┐  ┌──┐  ┌──┐
clk:    │  │  │  │  │  │  │  │  │  │
    ────┘  └──┘  └──┘  └──┘  └──┘  └──
        ↑     ↑     ↑     ↑     ↑
      上升沿  上升沿  上升沿  上升沿  上升沿
  • Frequency: 100 MHz, or 100 million cycles per second
  • Period: 10 ns (the waveform repeats every 10 ns)
  • Rising edge: The instant at which the signal changes from 0 to 1

The clock acts as the circuit's “heartbeat.” Our design advances one step at a time on its rising edges.

Constraint-file syntax:

set_property PACKAGE_PIN P17 [get_ports clk]
set_property IOSTANDARD LVCMOS33 [get_ports clk]

2. New Syntax: always @(posedge clk or negedge rst_n)

2.1 Basic Form

In previous exercises, always @(*) described a circuit in which an output changed immediately when an input changed. The following construct allows a circuit to change automatically, one clock cycle at a time:

always @(posedge clk or negedge rst_n) begin
    if (!rst_n)
        // 复位:把寄存器设为初始值
    else
        // 正常工作:在每个时钟上升沿执行一次
end

Line by line:

  • posedge clk: Execute the operations between begin...end on every rising edge of the clock.
  • negedge rst_n: Execute the reset immediately when rst_n goes low (when the reset button is pressed).
  • if (!rst_n): If the reset signal is low (rst_n = 0), clear all registers or assign their initial values.
  • else: Operate normally while reset is inactive.

2.2 Reset Convention

This course consistently uses an active-low reset, named rst_n (n indicates negative/active-low):

Operation Syntax or value
Port declaration input rst_n
Sensitivity list always @(posedge clk or negedge rst_n)
Reset condition if (!rst_n)
Button pressed on the board rst_n = 0 (reset asserted)
Button released rst_n = 1 (normal operation)

The EGO1 development board has a dedicated active-low reset button connected to pin P15, as shown below.

image-20260327135841471

2.3 Assignment Rules

Inside an always @(posedge clk or negedge rst_n) block, use the non-blocking assignment operator <=:

always @(posedge clk or negedge rst_n) begin
    if (!rst_n)
        count <= 4'd0;       // 用 <=
    else
        count <= count + 1;  // 用 <=
end

A simple rule to remember:

  • Combinational always @(*) block → use =
  • Sequential always @(posedge clk ...) block → use <=
  • Do not mix the two.

2.4 The Difference Between = and <=

Verilog assignments fall into two categories:

Category Where Operator LHS signal type
Continuous assignment assign statement (dataflow) = must be wire
Procedural assignment inside an always block (behavioral) = or <= must be reg

Procedural assignments come in two flavors:

  • Blocking assignment =: executes sequentially — each statement completes before the next one runs, so a later statement sees the result of the earlier ones (just like C)
  • Nonblocking assignment <=: executes concurrently — all right-hand sides are evaluated using the old values from the start of the time step, and all left-hand sides are updated simultaneously at the end of the step

2.4.1 Why does combinational logic use =?

// Correct: blocking assignment for combinational logic
always @(*) begin
    x = a;          // assign x first
    x = x & b;      // update x to x & b, i.e., a & b
    x = x | c;      // each step depends on the new value from the previous one
end

79185149696

With blocking assignment, each statement depends on the new value produced by the previous one — exactly the behavior that cascaded logic needs. If <= were used by mistake, the later statements would use the old value, and the circuit would behave incorrectly.

// Wrong: nonblocking assignment for combinational logic
always @(*) begin
    x <= a;
    x <= x & b;
    x <= x | c;
end

79185150706

2.4.2 Why does sequential logic use <=?

Consider a two-stage shift register:

// Wrong: blocking assignment in sequential logic
always @(posedge clk) begin
    q1 = d;
    q2 = q1;    // q1 has already been updated, so q2 gets the new value
                // → q1 and q2 both equal d: two flip-flops in parallel!
end

79185133856

// Correct: nonblocking assignment in sequential logic
always @(posedge clk) begin
    q1 <= d;
    q2 <= q1;   // q2 gets the old value of q1 → d → q1 → q2: a true shift register
end

79185134653

With nonblocking assignment, both right-hand sides use the old values and both update simultaneously at the clock edge — exactly how real flip-flops behave; swapping the two statements makes no difference. With blocking assignment, you would have to carefully reorder the statements just to make it work — very error-prone.

So use the assignment operators correctly: = for combinational logic, <= for sequential logic.

2.5 The reg Type

A signal assigned in an always @(posedge clk ...) block is synthesized into an actual register. It remembers the value from the preceding clock cycle and updates on each clock edge. Therefore, an output assigned in this type of block must be declared as reg.


3. Counter Design

3.1 4-Bit Binary Counter

The simplest counter increments on every rising edge of the clock:

module counter_4bit (
    input            clk,
    input            rst_n,
    output reg [3:0] count
);
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            count <= 4'd0;
        else
            count <= count + 1'd1;
    end
endmodule

Behavior: After reset, count = 0. It then increments on every clock edge. After reaching 15, it overflows to 0 and repeats.

3.2 Modulo-N Counter

To return to zero after a particular value—for example, to count from 0 through 9—add a condition:

module counter_mod10 (
    input            clk,
    input            rst_n,
    output reg [3:0] count
);
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            count <= 4'd0;
        else if (count == 4'd9)
            count <= 4'd0;       // 到9归零
        else
            count <= count + 1'd1;
    end
endmodule

3.3 Parameterized Modulo-N Counter with Enable and Carry

In a practical project, a counter usually needs an enable signal (en) that controls whether it counts and a carry output (carry) for cascading several counters:

module counter_mod #(parameter MOD = 10) (
    input            clk,
    input            rst_n,
    input            en,
    output reg [3:0] count,
    output           carry
);
    assign carry = (count == MOD - 1) && en;

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            count <= 4'd0;
        else if (en) begin
            if (count == MOD - 1)
                count <= 4'd0;
            else
                count <= count + 1'd1;
        end
    end
endmodule

Example instantiation:

counter_mod #(.MOD(10)) u_cnt10 (
    .clk(clk), .rst_n(rst_n), .en(enable),
    .count(count_out), .carry(carry_out)
);

4. Clock Divider Design

4.1 Why Do We Need a Clock Divider?

The EGO1 clock operates at 100 MHz (100 million clock cycles per second), but practical applications require much lower rates:

Application Target frequency Required count
LED blinking 1 Hz 100,000,000
Seven-segment display scanning ~1 kHz 100,000
Stopwatch time base 100 Hz 1,000,000

A clock divider is a counter that outputs a pulse when it reaches its terminal count.

4.2 Clock Division Principle

To divide 100 MHz down to 1 Hz:

  • 1 Hz means one output pulse per second.
  • A 100 MHz clock has 100 million clock cycles per second.
  • Therefore, output one pulse after counting 100,000,000 cycles.

4.3 Clock Divider Implementation with a Pulse Output

module clk_div #(parameter MAX_COUNT = 100_000_000) (
    input      clk,
    input      rst_n,
    output reg tick      // 分频后的单周期脉冲
);
    reg [31:0] cnt;

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            cnt  <= 32'd0;
            tick <= 1'b0;
        end else if (cnt == MAX_COUNT - 1) begin
            cnt  <= 32'd0;
            tick <= 1'b1;    // 计满,产生一个脉冲
        end else begin
            cnt  <= cnt + 1'd1;
            tick <= 1'b0;    // 其余时刻保持低
        end
    end
endmodule

tick is high for only one clock cycle when the terminal count is reached and remains low at all other times. This is a single-cycle enable pulse.

parameter defines a constant that can be changed when the module is instantiated. The same source code can therefore support different configurations without modification, greatly improving reuse.

Important: Do not use a divided signal as the clock for another module (for example, always @(posedge slow_clk)). All modules should share the system clock clk, with the tick pulse used as an enable.

4.4 Parameterized Examples

// 1Hz —— LED闪烁
clk_div #(.MAX_COUNT(100_000_000)) u_1hz (
    .clk(clk), .rst_n(rst_n), .tick(tick_1hz)
);

// 1kHz —— 数码管扫描
clk_div #(.MAX_COUNT(100_000)) u_1khz (
    .clk(clk), .rst_n(rst_n), .tick(tick_1khz)
);

// 100Hz —— 秒表基准
clk_div #(.MAX_COUNT(1_000_000)) u_100hz (
    .clk(clk), .rst_n(rst_n), .tick(tick_100hz)
);

5. Testbench Simulation Techniques

5.1 Generating a Clock

reg clk;
initial clk = 0;
always #5 clk = ~clk;   // 周期10ns = 100MHz

#5 introduces a 5 ns delay. Toggling the signal every 5 ns produces a clock with a 10 ns period.

5.2 Generating an Active-Low Reset

reg rst_n;
initial begin
    rst_n = 0;      // 一开始按下复位(低有效)
    #25;
    rst_n = 1;      // 松开复位,开始正常工作
end

5.3 Accelerating Simulation

Dividing 100 MHz down to 1 Hz requires simulation of 100 million clock cycles and is extremely slow. Use a much smaller divisor during simulation:

// 仿真时:MAX_COUNT = 10,10个周期就出一个tick
clk_div #(.MAX_COUNT(10)) u_div_sim (
    .clk(clk), .rst_n(rst_n), .tick(tick)
);

5.4 Complete Testbench Example

`timescale 1ns/1ps

module tb_counter_4bit();
    reg        clk;
    reg        rst_n;
    wire [3:0] count;

    // 实例化
    counter_4bit uut (
        .clk   (clk),
        .rst_n (rst_n),
        .count (count)
    );

    // 100MHz 时钟
    initial clk = 0;
    always #5 clk = ~clk;

    // 测试序列
    initial begin
        $monitor("time=%4d: rst_n=%b count=%d", $time, rst_n, count);

        rst_n = 0;          // 复位
        #25;
        rst_n = 1;          // 松开复位,开始计数
        #200;               // 观察计数
        rst_n = 0;          // 再次复位
        #20;
        rst_n = 1;
        #100;
        $finish;
    end
endmodule

6. Laboratory Exercises

Exercise 1: LED Blinking at 1 Hz

Requirement: Make one LED on the EGO1 blink at 1 Hz (on for 0.5 seconds and off for 0.5 seconds).

Steps

  1. Write the code: Create clk_div.v and led_blink.v.
  2. Simulate and verify: Write a testbench, change the division factor to 10, and inspect the tick and led transition waveforms.
  3. Assign pins and verify on the board:
  4. clk → P17 (100 MHz crystal oscillator)
  5. rst_n → P15 (reset button)
  6. led → Assign to one LED
  7. Synthesize, generate the bitstream, and program the board, then observe the LED blinking.

Exercise 2 (Optional): 4-Bit Binary Counter with LED Output

Requirement: Use four LEDs to display a 4-bit binary counter that increments once per second.

Steps

  1. Write the code: Use a clock divider to generate a 1 Hz pulse. Increment the 4-bit counter on each pulse and connect its value to four LEDs.
  2. Simulate and verify: Verify the repeating sequence 0→1→2→...→15→0.
  3. Verify on the board: Observe the LEDs displaying the count in binary, with one complete cycle taking approximately 16 seconds.

Question: What must be changed to make the counter count only from 0 through 9 (modulo 10)?


Appendix: Frequently Asked Questions

  • Q: What happens when the counter overflows? A: A 4-bit counter ([3:0]) automatically returns to 0 when incremented after 15. To return to zero after a specific value, add an if (count == target_value) condition.

  • Q: Why does the clock divider produce no pulse in simulation? A: Check whether the simulation runs long enough. During simulation, use a small division factor such as MAX_COUNT = 10 instead of simulating 100 million cycles.

  • Q: Can the output of a clock divider be used directly as a clock? A: This is strongly discouraged. An FPGA design should use a single global clock, clk, and use the divider's tick pulse as an enable. Multiple clocks introduce clock-domain-crossing problems and are a common source of errors.

  • Q: Why use rst_n (active-low) instead of rst (active-high)? A: The reset button on the EGO1 development board outputs a low level while pressed and a high level when released. An active-low reset matches this hardware behavior: pressing the button resets the circuit, and releasing it resumes normal operation.