RTL Design Code
Ready-to-study Verilog RTL: datapaths, converters, FSMs, FIFOs, interfaces and project roadmaps.
Ready-to-study Verilog RTL: datapaths, converters, FSMs, FIFOs, interfaces and project roadmaps.
21 articles · 4 groupsA crash course in Verilog: language basics, coding style, simulation behaviour and worked book solutions.
13 articles · 3 groupsThis design functions as an efficient hardware bridge interfacing an upstream synchronous data FIFO with a downstream SPI peripheral device. The system automatically fetches data bytes from the FIFO when available, converts them from parallel to serial, and handles full transaction execution using standard SPI Mode 0 (CPOL=0, CPHA=0).
[ Upstream FIFO ] [ FIFO to SPI Bridge ] [ Downstream SPI ]
┌───────────────┐ ┌──────────────────────┐ ┌────────────────┐
│ empty ├───────────────────>│ empty │ │ │
│ rd_data[7:0]├───────────────────>│ fifo_data[7:0] │ │ │
│ rd_en │<───────────────────┤ fifo_rd_en sclk├────────────────>│SCLK │
└───────────────┘ │ mosi├────────────────>│MOSI │
│ ss├────────────────>│SS │
└──────────────────────┘ └────────────────┘
fifo_to_spi_bridge.v)// ============================================================================
// Module Name: fifo_to_spi_bridge
// Description: Bridge that reads 8-bit data from a FIFO and transmits it
// over a standard SPI interface (SPI Mode 0: CPOL=0, CPHA=0).
// ============================================================================
module fifo_to_spi_bridge #(
parameter CLK_DIVIDE = 4 // System clock division factor for SCLK generation
)(
// Clock and Reset
input wire clk, // System Clock
input wire rst_n, // Active Low Asynchronous Reset
// FIFO Interface
input wire [7:0] fifo_data, // 8-bit parallel data from FIFO
input wire fifo_empty, // Empty flag from upstream FIFO
output reg fifo_rd_en, // Read enable strobe to FIFO
// SPI Interface
output reg spi_sclk, // SPI Serial Clock
output reg spi_mosi, // SPI Master Out Slave In
output reg spi_ss // SPI Slave Select / Chip Select (Active Low)
);
// --- State Machine Definitions ---
localparam STATE_IDLE = 3'b000;
localparam STATE_FETCH = 3'b001;
localparam STATE_WAIT_FIFO = 3'b010;
localparam STATE_TX_BIT = 3'b011;
localparam STATE_DONE = 3'b100;
reg [2:0] current_state, next_state;
// --- Internal Registers & Counters ---
reg [7:0] shift_reg; // Parallel-to-serial shift register
reg [2:0] bit_counter; // Tracks which of the 8 bits is transmitting
reg [7:0] sclk_divider; // Clock divider counter for SCLK generation
reg sclk_en; // Enables internal SCLK ticking
reg sclk_edge_toggle; // Toggles on every half-period of SCLK
// --- Clock Divider logic for SPI SCLK ---
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
sclk_divider <= 0;
sclk_edge_toggle <= 0;
end else if (sclk_en) begin
if (sclk_divider == (CLK_DIVIDE/2) - 1) begin
sclk_divider <= 0;
sclk_edge_toggle <= 1'b1;
end else begin
sclk_divider <= sclk_divider + 1;
sclk_edge_toggle <= 1'b0;
end
end else begin
sclk_divider <= 0;
sclk_edge_toggle <= 1'b0;
end
end
// --- State Machine Sequential Logic ---
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
current_state <= STATE_IDLE;
end else begin
current_state <= next_state;
end
end
// --- State Machine Combinational Logic ---
always @(*) begin
next_state = current_state;
case (current_state)
STATE_IDLE: begin
if (!fifo_empty) next_state = STATE_FETCH;
end
STATE_FETCH: next_state = STATE_WAIT_FIFO;
STATE_WAIT_FIFO: next_state = STATE_TX_BIT;
STATE_TX_BIT: begin
if (bit_counter == 3'd7 && spi_sclk == 1'b1 && sclk_edge_toggle)
next_state = STATE_DONE;
end
STATE_DONE: begin
if (sclk_edge_toggle) next_state = STATE_IDLE;
end
default: next_state = STATE_IDLE;
endcase
end
// --- Datapath Control ---
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
fifo_rd_en <= 1'b0;
shift_reg <= 8'h00;
bit_counter <= 3'd0;
sclk_en <= 1'b0;
spi_sclk <= 1'b0;
spi_mosi <= 1'b0;
spi_ss <= 1'b1;
end else begin
case (current_state)
STATE_IDLE: begin
fifo_rd_en <= 1'b0;
bit_counter <= 3'd0;
sclk_en <= 1'b0;
spi_sclk <= 1'b0;
spi_mosi <= 1'b0;
spi_ss <= 1'b1;
end
STATE_FETCH: begin
fifo_rd_en <= 1'b1;
end
STATE_WAIT_FIFO: begin
fifo_rd_en <= 1'b0;
shift_reg <= fifo_data;
spi_ss <= 1'b0;
end
STATE_TX_BIT: begin
sclk_en <= 1'b1;
if (sclk_edge_toggle) begin
if (spi_sclk == 1'b0) begin
spi_sclk <= 1'b1;
end else begin
spi_sclk <= 1'b0;
shift_reg <= {shift_reg[6:0], 1'b0};
bit_counter <= bit_counter + 1;
end
end
spi_mosi <= shift_reg[7];
end
STATE_DONE: begin
if (sclk_edge_toggle) begin
sclk_en <= 1'b0;
spi_ss <= 1'b1;
spi_mosi <= 1'b0;
end
end
endcase
end
end
endmodule
tb_fifo_to_spi_bridge.v)`timescale 1ns / 1ps
module tb_fifo_to_spi_bridge;
// Inputs
reg clk;
reg rst_n;
reg [7:0] fifo_data;
reg fifo_empty;
// Outputs
wire fifo_rd_en;
wire spi_sclk;
wire spi_mosi;
wire spi_ss;
// Instantiate Unit Under Test (UUT)
fifo_to_spi_bridge #(
.CLK_DIVIDE(4)
) uut (
.clk(clk),
.rst_n(rst_n),
.fifo_data(fifo_data),
.fifo_empty(fifo_empty),
.fifo_rd_en(fifo_rd_en),
.spi_sclk(spi_sclk),
.spi_mosi(spi_mosi),
.spi_ss(spi_ss)
);
// Generate Clock (50MHz -> Period = 20ns)
always #10 clk = ~clk;
initial begin
clk = 0;
rst_n = 0;
fifo_data = 8'h00;
fifo_empty = 1;
#40;
rst_n = 1;
#40;
// Transmit Data Byte 0xA5
wait(clk);
fifo_data = 8'hA5;
fifo_empty = 0;
@(posedge fifo_rd_en);
@(negedge clk);
fifo_empty = 1;
@(posedge spi_ss);
#100;
$finish;
end
endmodule
STATE_WAIT_FIFO cycle, securing high-speed immunity against downstream glitches or unexpected timing changes on the external FIFO lines.CLK_DIVIDE design parameter allows engineers to adapt serial output frequencies to meet the timing restrictions of various targeted host chips without breaking the main system fabric layout.Select a subject domain below to access specific technical test modules.
Test plans, functional coverage metrics, and simulation-based strategy tracks.
Combinational logic structures, state machines, and fundamentals of sequential circuits.
Setup/hold constraints, timing violations, false paths, and SDC constraints.
Universal Verification Methodology components, TLM ports, phases, and factories.
Quizzes on System Verilog syntax
Metastability issues, multi-clock synchronization techniques, and asynchronous FIFOs.
1000 Questions, easy/medium/hard levels , interview questions on PnR
Translation mechanics, logic optimization steps, and gate-level netlist generation.
Master your foundations across multiple modules including Verification, Static Timing Analysis (STA), UVM Framework, CDC, Logic Synthesis, and RTL coding tracks.
Welcome to my digital design blog! I share in-depth articles on RTL design, timing analysis, ASIC/FPGA concepts, and interview preparation.
This sample project demonstrates a complete RTL design flow for a 4-bit × 4-bit binary multiplier using Verilog. It includes the design specification, the synthesizable Verilog implementation, a self-checking testbench, and sample simulation results.
multiplier_project/
├── spec.md # Design Specification
├── multiplier_4x4.v # Synthesizable RTL
├── multiplier_tb.v # Self-checking Testbench
└── run.tcl # Icarus Verilog simulation script
Design a combinational 4-bit binary multiplier that computes the product of two unsigned 4-bit operands using the partial product and sum approach. The design must be fully combinational, synthesizable, and free of latches.
A[3:0] and B[3:0].P[7:0] = A × B.P = 8'b00000000.P = 8'b11100001.| Signal | Direction | Width | Description |
|---|---|---|---|
| A | Input | 4 | First unsigned operand |
| B | Input | 4 | Second unsigned operand |
| P | Output | 8 | Product (A × B) |
initial blocks, no delays in RTL).The multiplication is performed as follows:
The following module implements the 4-bit multiplier using a parameterized partial-product approach.
// File: multiplier_4x4.v
// Description: 4-bit x 4-bit unsigned multiplier
// Algorithm: Partial product + adder tree
module multiplier_4x4 #(
parameter DATA_WIDTH = 4
) (
input wire [DATA_WIDTH-1:0] A,
input wire [DATA_WIDTH-1:0] B,
output wire [2*DATA_WIDTH-1:0] P
);
// ------------------------------------------------------------------
// Partial product generation
// PP[i][j] = A[i] & B[j]
// ------------------------------------------------------------------
reg [DATA_WIDTH-1:0] pp_row [0:DATA_WIDTH-1];
integer i, j;
always @(*) begin
for (i = 0; i < DATA_WIDTH; i = i + 1) begin
for (j = 0; j < DATA_WIDTH; j = j + 1) begin
pp_row[i][j] = A[i] & B[j];
end
end
end
// ------------------------------------------------------------------
// Shift and sum partial product rows
// Row i is shifted left by i positions
// ------------------------------------------------------------------
wire [2*DATA_WIDTH-1:0] shifted_pp [0:DATA_WIDTH-1];
generate
genvar row;
for (row = 0; row < DATA_WIDTH; row = row + 1) begin : gen_shift
assign shifted_pp[row] = {2*DATA_WIDTH{1'b0}} |
({(2*DATA_WIDTH - DATA_WIDTH){1'b0}}, pp_row[row]) << row;
end
endgenerate
// ------------------------------------------------------------------
// Sum all shifted rows
// ------------------------------------------------------------------
wire [2*DATA_WIDTH-1:0] sum_row1, sum_row2, sum_row3;
assign sum_row1 = shifted_pp[0] + shifted_pp[1];
assign sum_row2 = shifted_pp[2] + shifted_pp[3];
assign sum_row3 = sum_row1 + sum_row2;
assign P = sum_row3;
endmodule
For quick verification or when synthesis tools handle multiplication optimization internally, the multiplier can be written as a single line:
module multiplier_simple #(
parameter DATA_WIDTH = 4
) (
input wire [DATA_WIDTH-1:0] A,
input wire [DATA_WIDTH-1:0] B,
output wire [2*DATA_WIDTH-1:0] P
);
assign P = A * B;
endmodule
* operator lets the synthesis tool optimize the multiplier structure (often using Wallace or Dadda trees).
The testbench applies a series of input vectors, compares the output with the expected result, and reports pass/fail status automatically.
// File: multiplier_tb.v
// Description: Self-checking testbench for 4x4 multiplier
`timescale 1ns / 1ps
module multiplier_tb;
// Parameters
localparam DATA_WIDTH = 4;
// Signals
reg [DATA_WIDTH-1:0] A;
reg [DATA_WIDTH-1:0] B;
wire [2*DATA_WIDTH-1:0] P;
// DUT Instantiation
multiplier_4x4 #(
.DATA_WIDTH(DATA_WIDTH)
) dut (
.A(A),
.B(B),
.P(P)
);
// Test vectors: {A, B, Expected_P}
reg [2*DATA_WIDTH-1:0] A_vec, B_vec;
integer i;
integer num_errors = 0;
integer num_tests = 0;
// Expected results lookup table
function [2*DATA_WIDTH-1:0] expected_product;
input [DATA_WIDTH-1:0] a;
input [DATA_WIDTH-1:0] b;
begin
expected_product = a * b;
end
endfunction
// Stimulus generation
initial begin
$display("==========================================");
$display(" 4-Bit Multiplier Testbench");
$display("==========================================");
// Test case 1: Zero multiplication
A = 4'd0; B = 4'd0;
#10;
check_result(A, B, "Test 1: 0 x 0");
// Test case 2: One times one
A = 4'd1; B = 4'd1;
#10;
check_result(A, B, "Test 2: 1 x 1");
// Test case 3: Maximum value
A = 4'd15; B = 4'd15;
#10;
check_result(A, B, "Test 3: 15 x 15");
// Test case 4: Mixed values
A = 4'd7; B = 4'd3;
#10;
check_result(A, B, "Test 4: 7 x 3");
// Test case 5: Identity
A = 4'd5; B = 4'd1;
#10;
check_result(A, B, "Test 5: 5 x 1");
// Exhaustive sweep: all 16x16 combinations
$display("\nStarting exhaustive sweep (256 cases)...");
for (i = 0; i < 16; i = i + 1) begin
A = i[3:0];
for (j = 0; j < 16; j = j + 1) begin
B = j[3:0];
#5;
check_result(A, B, "Exhaustive");
end
end
// Summary
$display("==========================================");
$display(" Test Summary");
$display("==========================================");
$display(" Total Tests : %0d", num_tests);
$display(" Errors : %0d", num_errors);
$display(" Status : %s",
(num_errors == 0) ? "PASSED ✔" : "FAILED ✘");
$display("==========================================");
if (num_errors == 0)
$finish(0);
else
$finish(1);
end
// Task to check result
task check_result(
input [DATA_WIDTH-1:0] a,
input [DATA_WIDTH-1:0] b,
input [$clog2(16*16)-1:0] test_name
);
wire [2*DATA_WIDTH-1:0] expected = expected_product(a, b);
begin
num_tests = num_tests + 1;
if (P === expected) begin
$display(" [%0d] A=%0d B=%0d P=%0d | Expected=%0d | PASS",
num_tests, a, b, P, expected);
end else begin
num_errors = num_errors + 1;
$display(" [%0d] A=%0d B=%0d P=%0d | Expected=%0d | FAIL",
num_tests, a, b, P, expected);
end
end
endtask
// Waveform dump
initial begin
$dumpfile("multiplier.vcd");
$dumpvars(0);
end
endmodule
Sample console output from running the testbench with Icarus Verilog:
# Compile
iverilog -o multiplier_sim multiplier_4x4.v multiplier_tb.v
# Run simulation
vvp multiplier_sim
# View waveform (optional, with GTKWave)
gtkwave multiplier.vcd
# From Vivado Tcl Console
create_project multiplier_proj -part xc7a35tcpg236-1
add_files multiplier_4x4.v multiplier_tb.v
set_property top multiplier_tb [current_fileset]
launch_simulation
run all
| Stage | Description | Tool |
|---|---|---|
| 1 | Specification | Markdown / Word |
| 2 | RTL Coding | Verilog-2001 |
| 3 | Functional Simulation | Icarus / ModelSim / Vivado |
| 4 | Synthesis | Yosys / Vivado / Quartus |
| 5 | Gate-Level Simulation (Optional) | Icarus / ModelSim |
| 6 | FPGA Implementation / Tape-out | Vivado / Quartus / Synopsys |
initial blocks, no #delay, no latches in synthesizable code.Continue your digital design learning journey:
A Digital PLL locks the output clock phase to a reference clock using a Phase Detector, a Digital Loop Filter (Integrator), and a Digitally Controlled Oscillator (DCO).
The core components of a digital PLL are:
`timescale 1ns / 1ps
/**
* ============================================================================
* Digital Phase-Llocked Loop (DPLL)
* ============================================================================
*
* Structure:
* 1. Phase Detector: Measures phase error between ref_clk and out_clk
* 2. Loop Filter: Digital integrator (accumulator)
* 3. DCO: Digitally Controlled Oscillator
*
* The DPLL adjusts the output clock's frequency/phase to match the
* reference clock, with a fixed division ratio N.
*
* ============================================================================
*/
module digital_pll #(
parameter integer DIV_RATIO = 2, // Output freq = Ref freq / DIV_RATIO
parameter integer ACC_WIDTH = 16, // Accumulator width
parameter integer LOCK_WINDOW = 16 // Cycles to confirm lock
)(
input wire ref_clk, // Reference clock
input wire rst_n, // Active-low reset
input wire enable, // PLL enable
output reg out_clk, // Output clock
output wire lock, // Lock indicator
output wire [ACC_WIDTH-1:0] ctrl_word // DCO control word (debug)
);
// =========================================================================
// Internal Signals
// =========================================================================
reg [ACC_WIDTH-1:0] accumulator;
reg out_clk_reg;
reg lock_flag;
// Phase detector signals
reg ref_clk_d, ref_clk_dd;
reg out_clk_d, out_clk_dd;
wire ref_rise = ref_clk_d & ~ref_clk_dd;
wire out_rise = out_clk_d & ~out_clk_dd;
// Tick counter for phase measurement
reg [ACC_WIDTH-1:0] tick_counter;
reg counting;
// Loop filter (integrator)
reg [ACC_WIDTH-1:0] integrator;
// Lock counter
reg [7:0] lock_counter;
// =========================================================================
// 1. Edge Detectors
// =========================================================================
always @(posedge ref_clk or negedge rst_n) begin
if (!rst_n) begin
ref_clk_d <= 1'b0;
ref_clk_dd <= 1'b0;
out_clk_d <= 1'b0;
out_clk_dd <= 1'b0;
end else begin
ref_clk_d <= ref_clk;
ref_clk_dd <= ref_clk_d;
out_clk_d <= out_clk;
out_clk_dd <= out_clk_d;
end
end
// =========================================================================
// 2. Phase Detector
// =========================================================================
// Measures the time difference between a reference edge and the
// most recent output edge by counting reference clock cycles.
always @(posedge ref_clk or negedge rst_n) begin
if (!rst_n) begin
tick_counter <= 0;
counting <= 1'b0;
end else if (enable) begin
if (ref_rise) begin
// Start counting at reference edge
tick_counter <= 0;
counting <= 1'b1;
end else if (counting) begin
if (out_rise) begin
// Stop at output edge
counting <= 1'b0;
else begin
tick_counter <= tick_counter + 1'b1;
end
end
else begin
tick_counter <= 0;
counting <= 1'b0;
end
end
// =========================================================================
// 3. Phase Error Calculation
// =========================================================================
// Expected ticks per ref cycle = DIV_RATIO
// Actual measured ticks = tick_counter
// Error = Expected - Actual
wire signed [ACC_WIDTH:0] raw_error =
$signed({1'b0, DIV_RATIO}) - $signed({1'b0, tick_counter});
// =========================================================================
// 4. Digital Loop Filter (Integrator)
// =========================================================================
// The integrator accumulates the phase error to produce the control
// word. This provides the integral action needed for zero steady-state
// error.
always @(posedge ref_clk or negedge rst_n) begin
if (!rst_n) begin
integrator <= 0;
else if (enable) begin
// Update integrator with clamping
wire signed [ACC_WIDTH+1:0] new_int =
$signed({1'b0, integrator}) + {1'b0, raw_error};
if (new_int > (1 << ACC_WIDTH) - 1)
integrator <= (1 << ACC_WIDTH) - 1;
else if (new_int < -(1 << ACC_WIDTH))
integrator <= 0;
else
integrator <= (new_int >= 0) ? new_int[ACC_WIDTH-1:0] :
(0 - (-new_int)[ACC_WIDTH-1:0]);
else begin
integrator <= 0;
end
end
assign ctrl_word = integrator;
// =========================================================================
// 5. Digitally Controlled Oscillator (DCO)
// =========================================================================
// The DCO accumulates the control word on every ref_clk cycle.
// When the accumulator overflows, the output clock toggles.
always @(posedge ref_clk or negedge rst_n) begin
if (!rst_n) begin
accumulator <= 0;
out_clk_reg <= 0;
end else if (enable) begin
accumulator <= accumulator + ctrl_word;
// Toggle output on overflow
if (accumulator + ctrl_word >= (1 << ACC_WIDTH))
out_clk_reg <= ~out_clk_reg;
else
out_clk_reg <= out_clk_reg;
end
end
assign out_clk = out_clk_reg;
// =========================================================================
// 6. Lock Detection
// =========================================================================
// Lock is declared when the phase error remains small for
// a consecutive number of cycles.
always @(posedge ref_clk or negedge rst_n) begin
if (!rst_n) begin
lock_counter <= 0;
else if (enable) begin
if ($abs(raw_error) <= 2) begin
if (lock_counter < LOCK_WINDOW)
lock_counter <= lock_counter + 1'b1;
else begin
lock_counter <= 0;
end
else begin
lock_counter <= 0;
end
end
assign lock = (lock_counter == LOCK_WINDOW);
endmodule
`timescale 1ns / 1ps
module digital_pll_tb;
// Parameters
parameter REF_PERIOD = 10; // 100 MHz reference
parameter DIV_RATIO = 2; // Output = 50 MHz
// Signals
reg ref_clk;
reg rst_n;
reg enable;
wire out_clk;
wire lock;
wire [15:0] ctrl_word;
// Instantiate DUT
digital_pll #(
.DIV_RATIO (DIV_RATIO),
.ACC_WIDTH (16),
.LOCK_WINDOW(16)
) dut (
.ref_clk (ref_clk),
.rst_n (rst_n),
.enable (enable),
.out_clk (out_clk),
.lock (lock),
.ctrl_word (ctrl_word)
);
// Reference Clock Generation
initial begin
ref_clk = 0;
forever #(REF_PERIOD/2) ref_clk = ~ref_clk;
end
// Stimulus
initial begin
rst_n = 0;
enable = 0;
// Reset
repeat (5) @(posedge ref_clk);
rst_n = 1;
// Enable PLL
repeat (5) @(posedge ref_clk);
enable = 1;
// Run until locked
wait (lock);
$display("PLL Locked at time %t", $time);
// Run for a while after lock
repeat (100) @(posedge ref_clk);
// Disable PLL
enable = 0;
repeat (10) @(posedge ref_clk);
$finish;
end
// Waveform Dump
initial begin
$dumpfile("pll.vcd");
$dumpvars(0);
end
endmodule
| Parameter | Description | Default |
|---|---|---|
DIV_RATIO |
Division ratio. Output frequency = Reference frequency / DIV_RATIO. | 2 |
ACC_WIDTH |
Bit width of the accumulator and integrator. Higher values give finer frequency resolution but slower lock time. | 16 |
LOCK_WINDOW |
Number of consecutive cycles with small phase error required to declare lock. | 16 |
ACC_WIDTH improves resolution but may slow down the lock time. Ensure the loop bandwidth is well below the Nyquist rate of the reference clock.ACC_WIDTH as small as possible while maintaining sufficient frequency resolution.