Module 5: Behavioral Verilog for Synthesis · 5.6 Modeling Finite State Machines in Verilog

Three Complete State Machines

This article implements the three state machines introduced in Section 3.3. The mathematical state representations translate directly into synthesizable Verilog modules and verification testbenches.

Example 1: Timed Traffic-Light Controller

The traffic light cycles through four sequential states: RED_ST, GREEN_ST, YELLOW_ST, and PED_ST. Each state persists for a duration configured by timer_in. The lamp outputs depend exclusively on the current state, forming a Moore machine (Figure 1).

Traffic light
Figure 1: Four states in a ring, each timed

`timescale 1ns / 1ps
`default_nettype none

module traffic_light (
    input  wire       clk,
    input  wire       rst_n,
    input  wire [2:0] timer_in,    // Clock cycles allocated per state
    output reg        red, green, yellow
);
    localparam [1:0] RED_ST    = 2'b00,
                     GREEN_ST  = 2'b01,
                     YELLOW_ST = 2'b10,
                     PED_ST    = 2'b11;

    reg  [1:0] state, next_state;
    reg  [2:0] timer_count;
    wire       timer_expired = (timer_count == 3'd0);

    // Sequential state register
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) state <= RED_ST;
        else        state <= next_state;
    end

    // Timer datapath: reloads on state transition, decrements otherwise
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            timer_count <= timer_in;
        else if (state != next_state)
            timer_count <= timer_in;
        else if (timer_count != 3'd0)
            timer_count <= timer_count - 1'b1;
    end

    // Combinational next-state transitions
    always @(*) begin
        next_state = state;
        case (state)
            RED_ST:    if (timer_expired) next_state = GREEN_ST;
            GREEN_ST:  if (timer_expired) next_state = YELLOW_ST;
            YELLOW_ST: if (timer_expired) next_state = PED_ST;
            PED_ST:    if (timer_expired) next_state = RED_ST;
            default:                      next_state = RED_ST;
        endcase
    end

    // Combinational Moore output decoding
    always @(*) begin
        red = 1'b0; green = 1'b0; yellow = 1'b0;
        case (state)
            RED_ST:    red    = 1'b1;
            GREEN_ST:  green  = 1'b1;
            YELLOW_ST: yellow = 1'b1;
            // PED_ST: all vehicular lamps remain dark
        endcase
    end
endmodule

The countdown timer operates as an integrated datapath counter alongside the control FSM.

module tb_traffic_light;
    reg        clk = 0, rst_n;
    reg  [2:0] timer_in;
    wire       red, green, yellow;

    traffic_light dut (
        .clk(clk),
        .rst_n(rst_n),
        .timer_in(timer_in),
        .red(red),
        .green(green),
        .yellow(yellow)
    );
    always #5 clk = ~clk;

    initial begin
        $dumpfile("tb.vcd");
        $dumpvars(0, tb_traffic_light);

        timer_in = 3'd2;
        rst_n = 0; @(negedge clk); rst_n = 1;

        repeat (20) begin
            @(negedge clk);
            $display("t=%0t state=%b red=%b green=%b yellow=%b", $time, dut.state, red, green, yellow);
        end
        $finish;
    end
endmodule

Each lamp remains illuminated for timer_in + 1 clock cycles. State transitions occur synchronously without intermediate combinational glitches.

Example 2: Sequence Detector with Overlapping Recognition

This circuit monitors a continuous serial bit stream and asserts output found when it detects the four-bit pattern 1011. The detector handles overlapping sequences. The final 1 bit of a valid pattern can serve as the initial 1 bit of a subsequent pattern (Figure 2).

Sequence detector
Figure 2: The detector; the arc from S101 on a 1 goes to S1, not IDLE

`timescale 1ns / 1ps
`default_nettype none

module seq_detector_1011 (
    input  wire clk, rst_n, bit_in,
    output reg  found
);
    localparam [2:0] IDLE = 3'd0, S1 = 3'd1, S10 = 3'd2, S101 = 3'd3;
    reg [2:0] state, next_state;

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) state <= IDLE;
        else        state <= next_state;
    end

    always @(*) begin
        next_state = state;
        found      = 1'b0;
        case (state)
            IDLE: if (bit_in)  next_state = S1;
            S1:   if (!bit_in) next_state = S10;        // Consecutive 1 keeps machine in S1
            S10:  if (bit_in)  next_state = S101;
                  else         next_state = IDLE;
            S101: if (bit_in) begin
                      found      = 1'b1;    // Mealy output: asserts based on state and bit_in
                      next_state = S1;      // Final bit starts subsequent match
                  end else begin
                      next_state = S10;     // Substring '10' forms reusable prefix
                  end
            default: next_state = IDLE;
        endcase
    end
endmodule

Because found is a Mealy output, it asserts immediately during the cycle when the final bit appears on the serial line.

module tb_seq_detector_1011;
    reg     clk = 0, rst_n, bit_in;
    wire    found;
    integer match_count = 0;

    seq_detector_1011 dut (
        .clk(clk),
        .rst_n(rst_n),
        .bit_in(bit_in),
        .found(found)
    );
    always #5 clk = ~clk;

    // Stream 10110111011 contains matches at bit offsets 0, 3, and 7
    reg [10:0] stream = 11'b10110111011;
    integer    i;

    initial begin
        $dumpfile("tb.vcd");
        $dumpvars(0, tb_seq_detector_1011);

        rst_n = 0; bit_in = 0; @(negedge clk); rst_n = 1;

        for (i = 10; i >= 0; i = i - 1) begin
            bit_in = stream[i];          // Apply input after falling clock edge
            #2;                          // Allow combinational output settling
            if (found) match_count = match_count + 1;
            @(negedge clk);
        end

        if (match_count == 3)
            $display("PASS: %0d matches", match_count);
        else
            $display("FAIL: %0d matches (expected 3)", match_count);

        $finish;
    end
endmodule

The testbench confirms three sequence matches in eleven bits due to overlapping transition resolution.

Example 3: Vending Machine Controller and Datapath Partitioning

The vending machine accepts nickels (5 cents), dimes (10 cents), and quarters (25 cents) using a 2-bit input coin_type. It dispenses an item when accumulated credit reaches 50 cents, and returns any excess change.

Rather than defining individual states for every cent amount, the design partitions control logic from the datapath:

  • Datapath: Accumulates numerical credit using an adder and register.
  • Controller: Manages deposit, dispense, and clear sequences.
`timescale 1ns / 1ps
`default_nettype none

// Datapath module: Accumulates currency credit in cents
module credit_datapath (
    input  wire       clk, rst_n,
    input  wire [1:0] coin_type,
    input  wire       clear_credit,
    output reg  [6:0] credit
);
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)            credit <= 7'd0;
        else if (clear_credit) credit <= 7'd0;
        else case (coin_type)
            2'b01:   credit <= credit + 7'd5;
            2'b10:   credit <= credit + 7'd10;
            2'b11:   credit <= credit + 7'd25;
            default: credit <= credit;
        endcase
    end
endmodule

// Controller module: Manages FSM sequencing
module vending_controller #(
    parameter [6:0] PRICE = 7'd50
) (
    input  wire       clk, rst_n,
    input  wire [1:0] coin_type,
    input  wire [6:0] credit,
    output reg        clear_credit,
    output reg        dispense,
    output reg  [6:0] change_out
);
    localparam [1:0] IDLE = 2'b00, ACCUMULATING = 2'b01, DISPENSING = 2'b10;
    reg [1:0] state, next_state;

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) state <= IDLE;
        else        state <= next_state;
    end

    always @(*) begin
        next_state   = state;
        clear_credit = 1'b0;
        dispense     = 1'b0;
        change_out   = 7'd0;
        case (state)
            IDLE:         if (coin_type != 2'b00) next_state = ACCUMULATING;
            ACCUMULATING: if (credit >= PRICE)    next_state = DISPENSING;
            DISPENSING: begin
                dispense     = 1'b1;
                change_out   = credit - PRICE;
                clear_credit = 1'b1;              // Datapath clears at this edge
                next_state   = IDLE;
            end
            default: next_state = IDLE;
        endcase
    end
endmodule

// Top-level structural wrapper
module vending_machine #(
    parameter [6:0] PRICE = 7'd50
) (
    input  wire       clk, rst_n,
    input  wire [1:0] coin_type,
    output wire       dispense,
    output wire [6:0] change_out
);
    wire       clear_credit;
    wire [6:0] credit;

    credit_datapath u_datapath (
        .clk(clk),
        .rst_n(rst_n),
        .coin_type(coin_type),
        .clear_credit(clear_credit),
        .credit(credit)
    );

    vending_controller #(.PRICE(PRICE)) u_controller (
        .clk(clk),
        .rst_n(rst_n),
        .coin_type(coin_type),
        .credit(credit),
        .clear_credit(clear_credit),
        .dispense(dispense),
        .change_out(change_out)
    );
endmodule

During the DISPENSING state, the controller raises dispense, presents the calculated change value, and asserts clear_credit.

module tb_vending_machine;
    reg        clk = 0, rst_n;
    reg  [1:0] coin_type;
    wire       dispense;
    wire [6:0] change_out;

    vending_machine dut (
        .clk(clk),
        .rst_n(rst_n),
        .coin_type(coin_type),
        .dispense(dispense),
        .change_out(change_out)
    );
    always #5 clk = ~clk;

    task insert_coin;
        input [1:0] c;
        begin
            coin_type = c;     @(negedge clk);
            coin_type = 2'b00; @(negedge clk);
        end
    endtask

    task expect_dispense;
        input [6:0] exp_change;
        integer guard;
        begin
            guard = 0;
            while (!dispense && guard < 10) begin
                @(negedge clk);
                guard = guard + 1;
            end
            if (dispense && change_out == exp_change)
                $display("PASS: dispensed, change=%0d", change_out);
            else
                $display("FAIL: dispense=%b change_out=%0d (expected change %0d)", dispense, change_out, exp_change);
            @(negedge clk);
        end
    endtask

    initial begin
        $dumpfile("tb.vcd");
        $dumpvars(0, tb_vending_machine);

        rst_n = 0; coin_type = 2'b00; @(negedge clk); rst_n = 1;

        insert_coin(2'b11); insert_coin(2'b11);                     // 50 cents exact payment
        expect_dispense(7'd0);

        insert_coin(2'b11); insert_coin(2'b11); insert_coin(2'b10); // 60 cents with 10 cents change
        expect_dispense(7'd10);

        $finish;
    end
endmodule

The testbench validates both exact payment and overpayment scenarios.

Summary of Module 5 Concepts

  1. Procedural blocks: All always blocks execute concurrently. Use blocking assignments (=) for combinational logic and nonblocking assignments (<=) for sequential logic.
  2. Sensitivity lists: Edge keywords (posedge, negedge) infer sequential flip-flops. Use always @(*) for combinational blocks. Add default assignments at the top of combinational blocks to prevent latch inference.
  3. Branching constructs: An if-else chain builds priority networks. A case statement decodes parallel conditions. Use casez for wildcard matching, and avoid casex.
  4. Loops: Constant-bound for loops unroll into parallel hardware. The repeat, while, and forever constructs operate in testbenches. Use generate for to replicate structural instances.
  5. Registers and pipelines: Synchronous registers capture settled combinational logic. Asynchronous resets assert immediately and must release synchronously. Pipelining increases clock frequency at the cost of additional latency cycles.
  6. Finite state machines: Partition FSMs into state storage, transition calculation, and output decoding. Declare state values with localparam. Include a default recovery branch to handle unmapped states safely.

This completes Module 5. Module 6 covers verification methodology, testbench architectures, and self-checking simulation techniques.

← Encoding and Safe State Machines