[Design 2] Getting Started with Verilog Digital Logic: Combinational Circuits, Sequential Circuits and FSMs

State diagram and timing of the operation unit's FSM

Written by

in

Digital logic design is the foundation of SoC and IP design: implementing the function you want with logic gates such as AND, OR, NOT and XOR, plus flip-flops.

Designers once drew gates by hand, one at a time. But since HDLs (Hardware Description Languages) and synthesis, which turns HDL into gates automatically, spread in the late 1980s, design is done one level of abstraction higher, at RTL (Register Transfer Level).

This post builds combinational circuits, sequential circuits and FSMs in turn using Verilog, the most widely used HDL, and finishes by designing a small unit that combines them.


How is design code different from verification code?

Verilog supports many levels of abstraction, from switches and gates to RTL and behavioral code. But not every construct can be turned into a chip.

Design Testbench
Purpose Implemented in real silicon Measures and verifies the design's behavior
Usable constructs Synthesizable constructs only Anything the simulator supports
Examples assign, always @(posedge clk) #10 delays, initial, $display, file I/O

A delay like #10 in design code works in simulation, but the synthesis tool ignores it, which makes simulation and the real chip behave differently. It is important to make a habit of writing design code in synthesizable form from the start. (See 22 SystemVerilog coding guidelines for synthesis, and why.)


Combinational and sequential circuits

Combinational and sequential circuits compared, and the usual synchronous structure that combines them
Figure 1. A combinational circuit's output changes as soon as its input changes; a sequential circuit stores values only on clock edges. Most real designs repeat "combinational logic → register → combinational logic → register".
Combinational Sequential
Clock Not used Used
Stores values No Yes (flip-flops, registers, memory)
Output changes Immediately when inputs change On clock edges
Examples Gates, adders, MUXes, decoders, encoders Registers, counters, clock dividers, FSMs

The region driven by one clock is called a clock domain, and a large chip is made of many clock domains.


Building combinational circuits

AND gate: assign

module and_gate (
  input  wire a,
  input  wire b,
  output wire y
);
  assign y = a & b;     // y changes as soon as a or b changes
endmodule

assign is a continuous assignment. The left side updates the moment the right side changes, which makes it a perfect fit for combinational logic.

Decoder: always @(*) and case

module decoder_2to4 (
  input  wire [1:0] a,
  output reg  [3:0] y
);
  always @(*) begin
    case (a)
      2'b00: y = 4'b0001;
      2'b01: y = 4'b0010;
      2'b10: y = 4'b0100;
      2'b11: y = 4'b1000;
    endcase
  end
endmodule

always @(*) runs whenever any signal read inside the block changes. When writing combinational logic with always, always use @(*). If you leave a signal out of the sensitivity list, simulation and synthesis results will differ.

💡 Writing output reg does not create a register (flip-flop). In Verilog, reg only means "a variable assigned inside an always block"; whether it actually becomes a flip-flop depends on how you describe it (whether it is assigned on a clock edge). Because of this confusion, SystemVerilog lets you use a single logic for both.

Tri-state buffer: the conditional operator ? :

module tri_state_inverter (
  input  wire a,
  input  wire en,
  output wire z
);
  assign z = en ? ~a : 1'bz;   // invert when en=1, high-impedance when 0
endmodule

1'bz (high-impedance) leaves the output disconnected. It is used on pins outside the chip or on shared buses, and usually not in logic inside the chip.

MUX: if-else

module mux2 (
  input  wire a,
  input  wire b,
  input  wire sel,
  output reg  y
);
  always @(*) begin
    if (sel) y = a;
    else     y = b;
  end
endmodule

⚠️ In an always block for combinational logic, if you do not assign a value in every case (for example, by leaving out the else), the synthesis tool creates a latch to remember the previous value. Unintended latches are a common cause of timing problems. Always add a default to case and an else to if, or assign default values on the first line of the block.

assign vs always, wire vs reg

assign always
Used for Combinational logic Combinational (@(*)) and sequential (@(posedge clk)) logic
Assigns to wire reg
Circuit produced Gates Gates, flip-flops, and (by mistake) latches
wire reg
Meaning A connection A variable assigned inside always/initial
How it is assigned assign, connected to a module output = or <= inside always
Initial value (simulation) z if not driven x

Input ports are wire by default, so input a and input wire a are the same. However, Verilog-2001 has a rule that automatically turns undeclared names into 1-bit wires, which lets typos slip by silently. Put `default_nettype none at the top of the file to catch these mistakes as compile errors.


Building sequential circuits

D flip-flop

module dff (
  input  wire clk,
  input  wire d,
  output reg  q
);
  always @(posedge clk) begin
    q <= d;           // store d only on the rising clock edge
  end
endmodule

A clock is a signal that repeats 0 and 1 at a fixed period, and it keeps the timing of the whole circuit in step. A 10ns period, for example, is 100MHz.

Blocking (=) and nonblocking (<=)

This is what confuses Verilog beginners most. The rule is simple.

  • In combinational logic (always @(*)), use = (blocking)
  • In sequential logic (always @(posedge clk)), use <= (nonblocking)
// shift register: the intent is a → b → c
always @(posedge clk) begin
  b <= a;     // nonblocking: read all right-hand values first,
  c <= b;     //              then update together at the end of the edge → a correct shift
end

If you write the same code with =, b changes first and that value goes straight into c, so the two flip-flops behave like one. Nonblocking assignment accurately mimics real hardware, where every flip-flop updates at the same instant.

Reset: asynchronous and synchronous

// asynchronous reset (active-low): resets immediately, regardless of the clock
module dff_async_rst (
  input  wire clk, rst_n, d,
  output reg  q
);
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) q <= 1'b0;
    else        q <= d;
  end
endmodule

// synchronous reset: resets only on a clock edge
module dff_sync_rst (
  input  wire clk, rst_n, d,
  output reg  q
);
  always @(posedge clk) begin
    if (!rst_n) q <= 1'b0;
    else        q <= d;
  end
endmodule
Asynchronous reset Synchronous reset
Responds As soon as the reset signal arrives At the next clock edge
Advantage Can reset even without a clock Simpler timing analysis, robust to glitches
Watch out Reset release must be synchronized to the clock (reset synchronizer) The reset pulse must last at least one clock

ASICs often use "asynchronous assert, synchronous de-assert". Which style to use is usually set by the project's coding rules.

Combinational + sequential: a register with enable

module dff_en (
  input  wire clk, rst_n, en, d,
  output reg  q
);
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n)  q <= 1'b0;
    else if (en) q <= d;      // keeps the previous value when en is 0
  end
endmodule

The synthesis tool builds the "keep the value when en is 0" behavior as a MUX + flip-flop (or with clock gating).

Two-stage pipeline

module two_stage (
  input  wire clk, rst_n, a, b, c,
  output reg  ff2
);
  reg ff1;                                  // reg because it is assigned in always

  always @(posedge clk) begin
    ff1 <= (a & b) ^ c;                     // stage 1: store the combinational result
  end

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) ff2 <= 1'b0;
    else if (a) ff2 <= ff1;                 // stage 2: conditional store
  end
endmodule

Module hierarchy: instantiating submodules

module add8 (
  input  wire [7:0] a, b,
  output wire [7:0] sum
);
  assign sum = a + b;
endmodule

module top (
  input  wire       clk, rst,
  input  wire [7:0] a, b,
  output reg  [7:0] out
);
  wire [7:0] sum;

  add8 u0_add8 (.a(a), .b(b), .sum(sum));  // connect ports by name

  always @(posedge clk or posedge rst) begin
    if (rst) out <= 8'd0;
    else     out <= sum;                   // store the sum in a register
  end
endmodule

Putting reusable blocks in one module per file makes them easier to read, debug, maintain and share. It is safer to connect ports by name (.a(a)) rather than by position.


FSMs (finite state machines)

An FSM (finite state machine) has a fixed number of states and changes state based on its inputs. Almost all control logic, such as protocol control and sequence handling, is an FSM.

  • State: a situation the system can be in (IDLE, READ, WRITE and so on)
  • Input: a signal that causes state changes
  • Output: a signal produced from the state (and inputs)
  • Transition: the next state, decided by the current state and the inputs

Moore and Mealy

Moore machine Mealy machine
Output depends on Current state only Current state + inputs
When the output changes When the state changes (may be one clock later) As soon as inputs change
Advantage Stable outputs, easier timing analysis Fewer states, faster response
Disadvantage May need more states Glitches on inputs can propagate to outputs

Writing an FSM: the 3-block style

FSMs are easiest to read and least error-prone when the state register, next-state logic and output logic are written separately.

module handshake_fsm (
  input  wire clk, rst_n, done,
  output wire ack
);
  localparam READY = 2'b00, TRANS = 2'b01, WRITE = 2'b10, READ = 2'b11;
  reg [1:0] state, nstate;

  // ① state register (sequential)
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) state <= READY;
    else        state <= nstate;
  end

  // ② next-state logic (combinational)
  always @(*) begin
    case (state)
      READY:   nstate = done ? TRANS : READY;
      TRANS:   nstate = done ? TRANS : WRITE;
      WRITE:   nstate = done ? READ  : WRITE;
      READ:    nstate = done ? READY : READ;
      default: nstate = READY;
    endcase
  end

  // ③ output logic (Mealy: state + input)
  assign ack = done && (state == READY || state == WRITE);
endmodule

State values never need to be changed from outside the module, so localparam fits better than parameter. In SystemVerilog, typedef enum shows state names directly in the waveforms, which makes debugging much easier.


Worked example: a 4-operation unit built with an FSM

Let's design a small block using everything so far.

Spec

Signal Direction Description
clk input Clock (10MHz)
rst_n input Reset (active-low)
in_valid input 1-clock pulse. in_a, in_b and mode are valid at this moment
in_a[7:0], in_b[7:0] input 8-bit data
mode[1:0] input 00: AND, 01: OR, 10: XOR, 11: NOR
out_o[7:0] output Result
out_valid output 1-clock pulse. out_o is valid at this moment

Design plan: it works with three states, WAIT → INDATA → OUTDATA. In WAIT, receiving in_valid stores the inputs; INDATA computes the result into a register; OUTDATA drives out_valid to 1.

State diagram and timing of the operation unit's FSM
Figure 2. State transitions and timing of the unit. Two clocks after in_valid arrives, out_valid and the result appear for one clock.
`default_nettype none

module logic_calc (
  input  wire       clk,
  input  wire       rst_n,
  input  wire       in_valid,
  input  wire [7:0] in_a,
  input  wire [7:0] in_b,
  input  wire [1:0] mode,
  output reg  [7:0] out_o,
  output reg        out_valid
);
  localparam WAIT = 2'd0, INDATA = 2'd1, OUTDATA = 2'd2;

  reg [1:0] state, nstate;
  reg [7:0] reg_a, reg_b, result;
  reg [1:0] reg_mode;

  // ① state register
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) state <= WAIT;
    else        state <= nstate;
  end

  // ② next-state logic
  always @(*) begin
    case (state)
      WAIT:    nstate = in_valid ? INDATA : WAIT;
      INDATA:  nstate = OUTDATA;
      OUTDATA: nstate = WAIT;
      default: nstate = WAIT;
    endcase
  end

  // ③ input capture (accept new inputs only in the WAIT state)
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      reg_a <= 8'h00; reg_b <= 8'h00; reg_mode <= 2'b00;
    end else if (state == WAIT && in_valid) begin
      reg_a <= in_a;  reg_b <= in_b;  reg_mode <= mode;
    end
  end

  // ④ operation (combinational)
  always @(*) begin
    case (reg_mode)
      2'b00:   result = reg_a & reg_b;
      2'b01:   result = reg_a | reg_b;
      2'b10:   result = reg_a ^ reg_b;
      default: result = ~(reg_a | reg_b);
    endcase
  end

  // ⑤ output register: computed in INDATA, driven during OUTDATA
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      out_o     <= 8'h00;
      out_valid <= 1'b0;
    end else begin
      out_valid <= (state == INDATA);
      if (state == INDATA) out_o <= result;
    end
  end
endmodule

`default_nettype wire

A testbench for this design is covered in Verilog testbenches: from writing one to waveform debugging, and verifying it with UVM in Getting started with UVM.

💡 You can think of this FSM as a drink vending machine. WAIT waits for a customer, INDATA takes the money and button press and picks the drink, OUTDATA dispenses it, and then it goes back to WAIT.


Next step: SystemVerilog

As designs grew more complex and verification demands rose, Verilog (IEEE 1364) was merged into and extended by SystemVerilog (IEEE 1800) after 2005. These features are especially useful for design.

Feature Effect
logic type One type, no more choosing between wire and reg
always_comb, always_ff, always_latch States the design intent; tools warn if the circuit differs from it
typedef enum FSM state names appear directly in waveforms
struct, packed arrays Handle complex data as a group
unique case, priority case Make the intent of case conditions explicit
.* port connection Connect ports with matching names in one go
interface Bundle many signals into one connection

On the verification side, it added classes (object orientation), randomization, assertions, coverage and DPI for connecting to C, which became the foundation of UVM.


Summary

  • Write design code with synthesizable constructs; testbenches can use anything.
  • Combinational logic: assign or always @(*) + =. Sequential logic: always @(posedge clk) + <=.
  • If a combinational always does not assign a value in every case, you get a latch.
  • reg means "a variable assigned in always", not "a flip-flop".
  • FSMs are easiest to read and safest in 3 blocks: state register / next state / output.

Further reading

Design (5 posts)

  1. The SoC Development Flow at a Glance: From Concept to Chip
  2. Getting Started with Verilog Digital Logic: Combinational Circuits, Sequential Circuits and FSMs Reading now
  3. Learning RTL Coding by Rewriting Verilog in SystemVerilog
  4. 22 SystemVerilog Coding Guidelines for Synthesis, and Why
  5. Compilers 101 for Hardware Engineers: All the Way to Verilog

See the full Tech Notes index

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *