0% found this document useful (0 votes)
192 views34 pages

SPI Master IP Core Design and Verification

This project report presents the RTL design and verification of an APB-interfaced SPI Master IP core, aimed at enabling synchronous serial communication between a host system and SPI-compatible peripherals. It details the architectural components, implementation considerations, and verification methodologies, emphasizing the core's compliance with APB and SPI protocols. The design is intended for integration into SoC architectures, providing a reusable and efficient solution for peripheral control in embedded systems.

Uploaded by

Lakshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
192 views34 pages

SPI Master IP Core Design and Verification

This project report presents the RTL design and verification of an APB-interfaced SPI Master IP core, aimed at enabling synchronous serial communication between a host system and SPI-compatible peripherals. It details the architectural components, implementation considerations, and verification methodologies, emphasizing the core's compliance with APB and SPI protocols. The design is intended for integration into SoC architectures, providing a reusable and efficient solution for peripheral control in embedded systems.

Uploaded by

Lakshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

APB INTERFACED SPI MASTER IP CORE

RTL DESIGN

BY

DARSHAN.N

ELECTRONICS ENGINEERING VLSI DESIGN AND TECHNOLOGY

24BVD0013

VELLORE INSTITUTE OF TECHNOLOGY

1
Project Report: APB-Interfaced SPI Master IP Core RTL Design
Abstract
This project report details the Register Transfer Level (RTL) design and
verification of an SPI (Serial Peripheral Interface) Master Intellectual Property
(IP) core, featuring an industry-standard APB (Advanced Peripheral Bus)
interface. The primary objective of this design is to provide a versatile and
reusable hardware block that facilitates synchronous serial communication
between a host system (via APB) and various SPI-compatible peripheral
devices. The report encompasses a thorough explanation of the SPI and APB
protocols, a detailed breakdown of the IP core's architectural components,
considerations in its RTL implementation, and a comprehensive verification
methodology employing a robust testbench. Included are descriptions of crucial
simulation waveforms, demonstrating the IP core's correct functional behavior
and adherence to protocol specifications. This IP core is designed for efficient
integration into System-on-Chip (SoC) architectures, addressing the need for
standardized and high-performance peripheral control.
Chapter 1: Introduction
1.1 Project Overview
Digital integrated circuits, particularly System-on-Chips (SoCs), are
increasingly complex, integrating various functional blocks onto a single silicon
die. To manage this complexity and accelerate design cycles, the concept of
Intellectual Property (IP) cores has become fundamental.
Understanding IP Cores: An IP core represents a pre-designed, pre-verified,
and reusable block of logic that performs a specific function. These cores can be
broadly categorized:
 Soft IP: Provided as synthesizable RTL code (like Verilog or VHDL).
They offer flexibility for customization but require synthesis and place-
and-route by the designer. This project focuses on designing a Soft IP.
 Firm IP: Provided as a netlist or a partially routed design. They offer
better performance predictability than soft IP but less flexibility.

2
 Hard IP: Provided as a fully laid-out and routed GDSII file. They offer
the highest performance and area optimization but are specific to a
foundry process and offer no flexibility.
The utilization of IP cores significantly reduces development time, lowers
design risks (as the IP is typically pre-verified), and enables designers to focus
on system-level integration rather than re-inventing common functionalities.
The SPI Master IP core developed in this project falls into the category of a
peripheral IP, serving as a dedicated interface block within a larger SoC.
Rationale for SPI: The Serial Peripheral Interface (SPI) is a synchronous serial
communication protocol widely adopted in embedded systems due to its
simplicity, high speed, and full-duplex capabilities. It typically involves a
Master device, which controls the communication, and one or more Slave
devices. Data is transferred bit by bit over dedicated lines, synchronized by a
clock signal provided by the Master. Key advantages of SPI include:
 Simplicity: Uses few wires, typically four.
 High Speed: Can achieve very high clock frequencies, limited by the
devices and interconnect.
 Full-Duplex: Allows simultaneous transmission and reception of data.
 No Addressing Overhead: For single slave scenarios, chip select is
simple. For multiple slaves, dedicated chip select lines are used.
SPI finds extensive application in connecting microcontrollers to various
peripherals such as:
 Serial Flash memory (e.g., for bootloaders, data storage)
 Analog-to-Digital Converters (ADCs) and Digital-to-Analog Converters
(DACs)
 Sensors (temperature, pressure, accelerometers)
 SD card interfaces
 LCD/OLED displays
Rationale for APB: To integrate peripheral IP cores like our SPI Master into an
SoC, a standardized on-chip communication mechanism is essential. The
Advanced Microcontroller Bus Architecture (AMBA) developed by ARM is a

3
widely used standard for this purpose. AMBA defines several bus protocols,
including AXI (Advanced eXtensible Interface) for high-performance
components, AHB (AMBA High-performance Bus) for high-bandwidth
components, and APB (Advanced Peripheral Bus) for lower-bandwidth
peripherals.
The APB was selected for this project due to its key characteristics:
 Simplicity: It is a low-complexity, non-pipelined, two-phase protocol,
making it easy to implement and integrate.
 Low Power: Its simpler transfer cycle generally consumes less power
compared to higher-performance buses.
 Peripheral Connectivity: It is specifically designed for connecting less
complex, slower peripherals that are accessed infrequently, where high
burst rates are not required.
By interfacing the SPI Master with APB, a standard bridge is established
between a high-performance processor core (which might reside on an
AXI/AHB bus) and a relatively slower peripheral. This standardized interface
facilitates plug-and-play integration, reusability across different SoC designs,
and simplifies software development for controlling the peripheral.
Problem Statement: In contemporary SoC development, there is a continuous
demand for reusable and reliable peripheral IP cores that can be efficiently
integrated into larger systems. Specifically, a flexible SPI Master IP core,
controllable via a standard on-chip bus like APB, is crucial for numerous
applications. The challenge lies in designing an RTL block that correctly
implements both the APB slave interface and the SPI master protocol, ensuring
robust data transfer, configurability, and proper status reporting, all while
maintaining an efficient and synthesizable architecture.
Objective: The primary objective of this project is to design, implement using
Register Transfer Level (RTL) descriptions (Verilog HDL), and thoroughly
verify an APB-interfaced SPI Master IP core. This IP core is intended to be:
 Fully Functional: Capable of transmitting and receiving data over the
SPI bus.
 Configurable: Supporting different SPI modes (CPOL/CPHA) and
programmable baud rates.

4
 Standard-Compliant: Adhering to both APB and SPI protocol
specifications.
 Verifiable: Demonstrating correct operation through extensive
simulation.
 Reusable: Designed with modularity and parameterization for ease of
integration into various SoC designs.
2.1.1 SPI Fundamentals:
 Synchronous Communication: The core characteristic of SPI is its
synchronous nature. A dedicated clock signal, generated by the Master
device, orchestrates the data transfer. Both the Master and the Slave
device(s) use this shared clock to synchronize their internal shift registers,
ensuring that data bits are valid and sampled at the precise moments. This
eliminates the need for complex timing recovery mechanisms often found
in asynchronous protocols.
 Full-Duplex Operation: SPI supports simultaneous transmission and
reception of data. As the Master shifts out a bit on its data output line, it
simultaneously shifts in a bit on its data input line from the Slave. This
allows for efficient bidirectional communication within the same clock
cycle.
 Master-Slave Architecture: The SPI bus operates under a strict Master-
Slave paradigm.
o Master Device: The Master initiates and controls the entire
communication. It generates the serial clock (SCK), selects the
target Slave device(s) using a Slave Select (SS) line, and
starts/stops the data transfer. A system can have only one Master at
any given time for a specific transaction.
o Slave Device(s): Slave devices are passive participants; they
respond only when selected by the Master. They do not generate
clock signals or initiate communication. Multiple Slave devices can
be connected to the same SPI bus, differentiated by their unique
Slave Select lines.
2.1.2 SPI Signals: The standard SPI interface typically employs four logical
signals:

5
 SCK (Serial Clock): This signal is the clock generated by the Master
device. It defines the rate at which data bits are transferred. The Slave
device uses this clock to know when to sample incoming data and when
to shift out outgoing data.
 MOSI (Master Out Slave In): This is the data line used by the Master to
send data to the Slave. From the Master's perspective, it is an output.
From the Slave's perspective, it is an input.
 MISO (Master In Slave Out): This is the data line used by the Slave to
send data back to the Master. From the Slave's perspective, it is an output.
From the Master's perspective, it is an input. In a single-Master, single-
Slave configuration, MISO is directly connected. In multi-slave systems,
the MISO lines of all slaves are typically tri-stated when not selected,
allowing the selected slave to drive the common MISO line.
 SS or CS (Slave Select / Chip Select): This active-low signal is generated
by the Master to select a particular Slave device for communication.
When SS for a specific slave is asserted (pulled low), that slave becomes
active and ready to communicate. All other slaves whose SS lines remain
high are deselected and ignore the SCK and MOSI signals, often tri-
stating their MISO output to prevent bus contention.
2.1.3 SPI Modes (CPOL and CPHA): The SPI protocol offers flexibility in
timing through its four modes of operation. These modes are determined by two
parameters: Clock Polarity (CPOL) and Clock Phase (CPHA). Both the Master
and the selected Slave device must be configured to the same SPI mode for
successful communication.
 CPOL (Clock Polarity): Defines the idle state of the SCK signal (the
state when no data is being transferred or between transfers).
o CPOL = 0: The SCK signal is idle low. The first clock edge in a
transfer is a rising edge.
o CPOL = 1: The SCK signal is idle high. The first clock edge in a
transfer is a falling edge.
 CPHA (Clock Phase): Defines the timing of data sampling and data
output relative to the SCK edges.

6
o CPHA = 0: Data is valid (stable) on the first clock edge of each
SCK cycle and sampled on that same first edge. Data is typically
shifted out on the transition before the first edge.
o CPHA = 1: Data is valid (stable) on the second clock edge of each
SCK cycle and sampled on that same second edge. Data is
typically shifted out on the first clock edge.
The four SPI modes are a combination of these parameters:

SPI SCK Idle Data Valid/Sampled Data Shifted Out


CPOL CPHA
Mode State On On

Mode 0 0 0 Low Rising edge Falling edge

Mode 1 0 1 Low Falling edge Rising edge

Mode 2 1 0 High Falling edge Rising edge

Mode 3 1 1 High Rising edge Falling edge

 Show SCK in its respective idle state (CPOL=0 or CPOL=1).


 Clearly mark the edges on which MOSI data is valid (i.e., when the
Master changes its MOSI output) and the edges on which MISO data is
sampled by the Master.

7
 Use distinct visual cues (e.g., vertical lines, arrows) to indicate the precise
sampling/output moments as determined by CPHA.
 example bit 1 or 0 being driven and sampled. Caption: Illustration of the
four SPI communication modes (0, 1, 2, 3), showing clock polarity, clock
phase, and the corresponding data valid and sampling edges for MOSI
and MISO signals.

2.1.4 Data Transfer Process: An SPI data transfer is a synchronous, bit-by-bit


exchange. For an 8-bit transfer (a common configuration), the process unfolds
as follows:
1. Slave Selection: The Master asserts the SS (or CS) line of the target
Slave device by pulling it low. This action signals to the Slave that it is
being addressed and should prepare for communication.
2. Clock Generation and Bit Exchange: The Master begins generating the
SCK signal according to the configured SPI mode.
o For each clock cycle:
 The Master places the next bit of data onto the MOSI line.
The timing of this data change (relative to SCK edges)
depends on CPHA.
 Simultaneously, the Slave places its next bit of data onto the
MISO line.
 Both the Master and the Slave sample the data on their
respective input lines (MISO for Master, MOSI for Slave) at
the appropriate SCK edge (determined by CPHA).
 This means that an 8-bit Master-to-Slave transfer also results
in an 8-bit Slave-to-Master transfer. Data is always
exchanged bidirectionally during active SCK cycles.
3. Transfer Completion: After all 8 bits (or the configured data length)
have been exchanged, the Master ceases generating SCK and de-asserts
the SS line by pulling it high. This signals the end of the current
transaction, and the Slave device typically becomes inactive.
2.2 Advanced Peripheral Bus (APB) Protocol

8
System Architecture and Design
This chapter describes the internal organization and functional blocks of the
APB-interfaced SPI Master IP core. Understanding this architecture is crucial
for comprehending how the IP processes commands from the APB bus and
translates them into SPI communication.
3.1 Top-Level Architecture of APB-SPI Master IP Core
The APB-SPI Master IP core acts as a bridge, translating high-level commands
from a host processor (communicating via APB) into the specific bit-level
sequences required for SPI communication with a peripheral device. Its top-
level architecture integrates several distinct functional blocks, each responsible
for a specific aspect of this translation and control.

 Left Side (APB Interface): Show PCLK, PRESETn, PSEL, PENABLE,


PWRITE, PADDR, PWDATA as inputs entering the main block, and
PRDATA, PSLVERR as outputs exiting. These signals should connect
directly to an internal block labeled "APB Interface".

9
 Right Side (SPI Interface): Show SCK, MOSI, SS as outputs exiting the
main block, and MISO as a bidirectional signal connecting to it. These
signals should connect to an internal block labeled "SPI State Machine"
or "SPI Core".
 Internal Blocks and Connections (within the main IP block):
o APB Interface: Connected to external APB signals. It has internal
control/data lines to "Control Logic" and "Register File".
o Control Logic: The central control unit. Receives
configuration/commands from "APB Interface" (via "Register
File") and generates control signals for "SPI State Machine", "TX
Data Buffer", "RX Data Buffer", and "Baud Rate Generator".
o Register File / Configuration Registers: Connected to "APB
Interface" for read/write access, and to "Control Logic" to provide
configuration values (e.g., baud rate divisor, SPI mode).
o TX Data Buffer (FIFO): Receives data from "APB Interface" (via
"Register File" write) and provides data to "SPI State Machine".
o RX Data Buffer (FIFO): Receives data from "SPI State Machine"
and provides data to "APB Interface" (via "Register File" read).
o Baud Rate Generator: Receives configuration from "Control
Logic" (via "Register File") and generates SCK for the "SPI State
Machine".
o SPI State Machine: Receives data from "TX Data Buffer",
generates MOSI, SCK, SS, and receives MISO. It then sends
received data to "RX Data Buffer".
o Reset Logic: A module overseeing all sequential logic, receiving
PRESETn and asserting internal reset signals to other blocks.

Explanation of Functional Blocks and Inter-Block Communication:


1. APB Interface Module:
o Purpose: This module serves as the primary gateway between the
external APB bus and the internal logic of the SPI Master IP. It
implements the APB slave protocol, responding to bus transactions

10
(reads and writes) initiated by an external APB Master (e.g., a
CPU). Its responsibilities include:
 Decoding PADDR to identify which internal register is being
targeted.
 Latching PWDATA during APB write cycles and storing it
into the appropriate internal register.
 Driving PRDATA with the contents of the requested internal
register during APB read cycles.
 Asserting PSLVERR if an attempt is made to access an
invalid address.
 Managing the PSEL and PENABLE signals to ensure correct
two-cycle APB transfers.
o Communication: It directly interacts with the internal Register
File, acting as the interface point for all configuration and data
exchange between the APB and the IP core.
2. Control Logic / Register File:
o Purpose: This central control unit acts as the brain of the IP core,
orchestrating operations based on the values stored in its memory-
mapped registers. It translates high-level commands received via
the APB Interface into specific control signals for the SPI State
Machine, Baud Rate Generator, and Data Buffers. It also
aggregates status information from these modules and makes it
available to the APB Master through status registers.
o Register File: This is a collection of internal registers that the APB
Master can read from and write to. These registers define the
operational parameters of the SPI Master and provide its current
status. (A detailed register map is provided in Section 3.2.1).
o Communication: Receives write data and addresses from the APB
Interface to configure itself. Provides read data back to the APB
Interface. Sends control signals (e.g., start_spi_transfer,
fifo_read_en, fifo_write_en, spi_mode_config) to the SPI State
Machine, Data Buffers, and Baud Rate Generator. Receives status

11
signals (e.g., tx_fifo_empty, rx_fifo_full, spi_busy) from other
blocks to update its status registers.
3. SPI State Machine:
o Purpose: This is the most critical module for implementing the SPI
protocol. It is responsible for generating the precise timing
sequence for all SPI signals (SCK, MOSI, MISO, SS) based on the
configured SPI mode (CPOL/CPHA) and the desired data transfer
length (e.g., 8-bit). It controls the bit-by-bit shifting of data.
o Communication: Receives data to be transmitted from the TX
Data Buffer. Drives the MOSI, SCK, and SS output signals.
Samples the MISO input signal. Passes received data to the RX
Data Buffer. Provides busy status to the Control Logic. Receives
start_transfer and spi_mode configurations from the Control Logic.
4. TX Data Buffer (FIFO):
o Purpose: This First-In, First-Out (FIFO) buffer temporarily stores
data bytes that are written by the APB Master and are waiting to be
transmitted over the SPI bus. It decouples the typically byte-
oriented, burst-like APB write operations from the bit-by-bit serial
SPI transmissions, allowing the APB Master to write data
asynchronously without waiting for each bit to be shifted out.
o Implementation: Typically consists of a memory array, a write
pointer, a read pointer, and logic to generate full and empty flags.
o Communication: The Control Logic writes data into this FIFO via
TX_DATA_REG. The SPI State Machine reads data from this
FIFO when it is ready to transmit. Provides empty status to the
Control Logic.
5. RX Data Buffer (FIFO):
o Purpose: This FIFO temporarily stores data bytes that have been
received from the SPI Slave device via the MISO line. It decouples
the bit-by-bit SPI reception from the potentially slower APB read
operations, allowing received data to accumulate until the APB
Master is ready to read it.

12
o Implementation: Similar to the TX FIFO, it consists of a memory
array, read/write pointers, and full/empty flags.
o Communication: The SPI State Machine writes received data into
this FIFO. The Control Logic reads data from this FIFO when the
APB Master reads RX_DATA_REG. Provides full status to the
Control Logic.
6. Baud Rate Generator:
o Purpose: This module is responsible for generating the precise
SCK signal frequency required for SPI communication. The SCK
frequency is derived by dividing down the main PCLK based on a
programmable divisor value.
o Implementation: It typically employs a counter that decrements
from the configured baud rate divisor value. When the counter
reaches zero, the SCK output toggles its state, and the counter is
reloaded.
o Communication: Receives the baud rate divisor value from the
Control Logic (via the SPI_BAUD_DIV_REG). Outputs the SCK
signal to the SPI State Machine.
7. Reset Logic:
o Purpose: The Reset Logic ensures that all sequential elements
within the IP core (registers, counters, state machines) are
initialized to a known, stable, and inactive state upon assertion of
the system reset signal (PRESETn). This is critical for reliable
power-up behavior and recovery from system failures.
o Implementation: It receives the external PRESETn signal and
generates internal synchronized reset signals that propagate to all
sensitive registers and state machines, ensuring a deterministic
startup.
Block-Level Design and Explanation
APB Interface Module
The APB Interface module serves as the primary interface between the host
system's APB bus and the internal registers of the SPI Master IP core. It acts as

13
an APB slave, diligently listening for bus transactions and responding according
to the APB protocol.
 Address Decoding: The module continuously monitors the PADDR
signal. When PSEL for this specific IP core is asserted, the PADDR is
decoded to determine which internal register is being targeted for a read
or write operation. This decoding typically involves comparing slices of
PADDR against predefined base addresses and offsets. For example, if
the IP's base address is 0x0000_0000, then an PADDR of 0x00 would
target SPI_CTRL_REG, 0x04 would target SPI_STATUS_REG, and so
on.
 Write Operations: During an APB write transaction (indicated by
PWRITE being high and PENABLE being high), the module latches the
PADDR and PWDATA. Based on the decoded address, the PWDATA is
then written to the corresponding internal register. For example, writing
to PADDR = 0x08 would store PWDATA into the TX_DATA_REG
(which typically pushes it into the TX FIFO).
 Read Operations: During an APB read transaction (indicated by
PWRITE being low and PENABLE being high), the module reads the
data from the internal register specified by PADDR. This data is then
driven onto the PRDATA bus, allowing the APB Master to sample it.
 Error Handling: The PSLVERR signal is asserted if an attempt is made
to access an invalid or unmapped address within the IP's address space.
This provides feedback to the APB Master about erroneous transactions.
 Register Access Control: The module also enforces access rights (read-
only, write-only, read/write) for each register as defined in the register
map. Attempts to write to a read-only register or read from a write-only
register might be ignored or trigger an error, depending on the design
choice.
Register Map: The following table details the memory-mapped registers
accessible via the APB interface. Each register serves a specific purpose in
controlling the SPI Master or reporting its status. All registers are assumed to be
32-bit wide for standard APB compatibility, though only relevant bits for the
SPI function are typically used.

14
Typ
Addre
e
Register Name ss Bit Fields & Description
(R/
Offset
W)

Bit 0: SPI_EN (Read/Write) - When set to '1',


enables the SPI Master functionality. When '0',
the SPI Master is disabled and its outputs
(SCK, MOSI, SS) are typically idle or tri-
stated. <br> Bit 1: LSB_FIRST (Read/Write) -
Controls data order. '1' for Least Significant Bit
first, '0' for Most Significant Bit first.
Bit 2: LOOPBACK_EN (Read/Write) - '1'
SPI_CTRL_REG 0x00 R/W enables internal loopback mode for self-testing
(MOSI connected to MISO internally). '0' for
normal operation.
Bit 3: INTR_TX_EN (Read/Write) - Enables
the transmit complete interrupt.
Bit 4: INTR_RX_EN (Read/Write) - Enables
the receive data ready interrupt.
Bits [31:5]: Reserved (Read as 0, writes
ignored)

Bit 0: BUSY (Read-Only) - '1' indicates an SPI


transfer is currently in progress. '0' when idle.
Bit 1: TX_EMPTY (Read-Only) - '1' indicates
the Transmit FIFO is empty. '0' if data is
present.
Bit 2: RX_FULL (Read-Only) - '1' indicates
SPI_STATUS_RE the Receive FIFO is full. '0' if space is
0x04 R available.
G
Bit 3: TX_OVERRUN (Read-Only, Clear-on-
Read) - '1' if an attempt was made to write data
to a full TX FIFO. Cleared automatically upon
read.
Bit 4: RX_UNDERRUN (Read-Only, Clear-
on-Read) - '1' if an attempt was made to read
data from an empty RX FIFO. Cleared
15
Typ
Addre
e
Register Name ss Bit Fields & Description
(R/
Offset
W)

automatically upon read.


Bit 5: INTR_TX (Read-Only, Clear-on-Read) -
'1' indicates a transmit complete interrupt event
has occurred. Cleared automatically upon read.
Bit 6: INTR_RX (Read-Only, Clear-on-Read) -
'1' indicates new data is available in the RX
FIFO (receive data ready interrupt). Cleared
automatically upon read.
Bits [31:7]: Reserved

Bit [7:0]: TX_DATA (Write-Only) - The 8-bit


data byte to be transmitted over the SPI bus.
SPI_TX_DATA_
0x08 W Writing to this register pushes the byte into the
REG
internal TX FIFO.
Bits [31:8]: Reserved (Writes ignored)

Bit [7:0]: RX_DATA (Read-Only) - The 8-bit


data byte received from the SPI bus. Reading
SPI_RX_DATA_
0x0C R from this register pops a byte from the internal
REG
RX FIFO.
Bits [31:8]: Reserved (Read as 0)

Bit [15:0]: BAUD_DIV (Read/Write) - A 16-


bit divisor value used by the Baud Rate
Generator to determine the SPI clock
SPI_BAUD_DIV
0x10 R/W frequency. The formula for SCK frequency is:
_REG
SCK_Frequency=PCLK_Frequency/(2times(B
AUD_DIV+1)).
Bits: Reserved

Bit 0: CPOL (Read/Write) - Clock Polarity. '0'


SPI_MODE_CFG
0x14 R/W for SCK idle low, '1' for SCK idle high.
_REG Bit 1: CPHA (Read/Write) - Clock Phase. '0'
for data sampled on the first edge, '1' for data

16
Typ
Addre
e
Register Name ss Bit Fields & Description
(R/
Offset
W)

sampled on the second edge.


Bits [31:2]: Reserved

Bit 0: SS_OVERRIDE (Read/Write) - '1'


enables manual control of the SS signal via
SS_VALUE. '0' enables automatic SS control
SPI_SS_CTRL_R by the SPI State Machine (default). <br> Bit 1:
0x18 R/W
EG SS_VALUE (Read/Write) - When
SS_OVERRIDE is '1', this bit directly controls
the SS output signal ('0' for active, '1' for
inactive). <br> Bits [31:2]: Reserved

Export to Sheets
3.2.2 SPI Control Logic and State Machine
The SPI Control Logic and its associated State Machine form the core
intelligence of the SPI Master. This block dictates the exact timing and sequence
of events on the SPI bus, ensuring compliance with the chosen SPI mode.
 Overall Purpose: To manage the flow of an SPI transaction from
initiation (when data is ready to be transmitted) to completion. It controls
the generation of SCK, the shifting of data onto MOSI, the sampling of
data from MISO, and the assertion/de-assertion of SS.
 State Machine Design: A finite state machine (FSM) is employed to
manage the sequential nature of SPI communication. The FSM transitions
between distinct states, each representing a stage in the SPI transfer. The
state transitions are triggered by internal events (e.g., bit counter reaching
zero, data available in TX FIFO) and external control signals (e.g., SPI
enable).
Typical FSM States:
o IDLE: This is the initial and default state. The SPI Master is
inactive, SCK is in its idle state (determined by CPOL), MOSI is
typically tri-stated or driven low, and SS is inactive high. The FSM
17
remains in this state, monitoring the TX_EMPTY flag of the TX
FIFO.
o START_TRANSFER: When the SPI_EN bit in SPI_CTRL_REG
is set to '1' and data becomes available in the TX FIFO (i.e.,
TX_EMPTY is '0'), the FSM transitions to this state. In this state,
the BUSY flag in SPI_STATUS_REG is asserted, SS is pulled low
(active), and the first data byte is loaded from the TX FIFO into an
internal transmit shift register. The Baud Rate Generator is enabled
to start SCK generation.
o BIT_TRANSFER (or SHIFTING_BITS): This is the operational
state where the actual bit-by-bit data transfer occurs. The FSM
remains in this state for 8 (or configured data width) clock cycles
of SCK.
 On each SCK cycle (specifically, on the appropriate edge
determined by CPHA):
 The most significant (or least significant, depending
on LSB_FIRST setting) bit of the transmit shift
register is driven onto MOSI.
 The bit present on MISO is sampled and shifted into
an internal receive shift register.
 The internal bit counter is decremented.
o END_TRANSFER (or COMPLETE): When the bit counter
reaches zero (indicating all bits of the current byte have been
transferred), the FSM transitions to this state. In this state:
 The SS signal is de-asserted (pulled high).
 The received byte (from the internal receive shift register) is
pushed into the RX FIFO.
 The BUSY flag in SPI_STATUS_REG is de-asserted.
 If the TX FIFO still contains more data, the FSM might
transition back to START_TRANSFER for a continuous
burst. Otherwise, it returns to the IDLE state.

18
 CPOL and CPHA Implementation: The CPOL and CPHA bits from
SPI_MODE_CFG_REG directly influence the state machine's output
logic for SCK and its timing for MOSI data changes and MISO sampling.
o CPOL determines the initial value of SCK when SS becomes active
and the value between transfers.
o CPHA dictates on which SCK edge (posedge or negedge) the FSM
should sample MISO and on which preceding edge it should
change MOSI. This typically involves using posedge SCK or
negedge SCK sensitive blocks or conditional logic within a single
posedge PCLK block.
 Shift Registers: Within the SPI State Machine, dedicated 8-bit shift
registers are implemented (mosi_shift_reg and miso_shift_reg).
o The mosi_shift_reg is loaded with a byte from the TX FIFO and
then shifts out one bit per SCK cycle to the MOSI pin.
o The miso_shift_reg collects one bit per SCK cycle from the MISO
pin. Once 8 bits are collected, the full byte is transferred to the RX
FIFO.
3.2.4 Baud Rate Generator
The Baud Rate Generator module is responsible for producing the Serial Clock
(SCK) signal at a precise frequency, as required by the SPI protocol. This
frequency is configurable via the SPI_BAUD_DIV_REG.
 Functionality: The module takes the high-frequency system clock
(PCLK) as its input and generates a divided-down clock signal, SCK,
whose frequency is determined by a programmable divisor.
 Implementation: The core of the Baud Rate Generator is a down-
counter.
1. The counter is loaded with the value programmed into the
BAUD_DIV field of the SPI_BAUD_DIV_REG. This value is
read and latched from the APB interface.
2. On each rising edge of PCLK, the counter decrements.
3. When the counter reaches zero, the SCK signal toggles its state
(from low to high, or high to low), and the counter is immediately

19
reloaded with the BAUD_DIV value. This process ensures a
consistent SCK frequency.
 Frequency Calculation: The relationship between the PCLK frequency,
the BAUD_DIV value, and the resulting SCK frequency is given by the
formula: SCK_Frequency=PCLK_Frequency/(2times(BAUD_DIV+1))
The (BAUD_DIV + 1) term accounts for the zero count in the divisor.
The 2 \times factor arises because the counter must count down twice
(once for the high phase of SCK and once for the low phase) to complete
a full SCK period. For example, if PCLK is 100 MHz and BAUD_DIV is
9, then SCK frequency would be
100MHz/(2times(9+1))=100MHz/20=5MHz.
Reset Logic
The Reset Logic module is crucial for ensuring the reliability and predictability
of the SPI Master IP core. Its primary function is to initialize all sequential
elements within the IP to a defined, safe, and inactive state upon assertion of the
system reset.
 Purpose:
o Initialization: After power-up or a system-level reset, the internal
state of all flip-flops and registers in a digital design is undefined.
Reset logic forces these elements into a known state, typically the
IDLE state for state machines and zero for data registers.
o Error Recovery: In the event of a system malfunction or
unexpected behavior, asserting the reset signal provides a
mechanism to bring the IP back to a safe operating point.
 Implementation: The PRESETn (Peripheral Reset, active low) signal is
the primary input to the Reset Logic.
o Synchronous Reset: In this design, a synchronous reset approach
is utilized. This means that the reset signal (PRESETn) is sampled
by PCLK, and all sequential elements are reset only on the active
edge of PCLK while PRESETn is asserted. This approach helps in
achieving better timing analysis and avoiding metastability issues
that can arise with asynchronous resets.

20
o When PRESETn is low (asserted), the Control Logic forces the SPI
State Machine to its IDLE state, clears all internal registers (e.g.,
TX_DATA_REG, RX_DATA_REG, BAUD_DIV_REG), resets the
FIFOs (making them empty), and de-asserts any active flags like
BUSY.
o When PRESETn goes high (de-asserted), the IP transitions from
the reset state to normal operation, waiting for APB commands.

RTL Design and Implementation


This chapter details the methodology and considerations involved in
transforming the architectural design of the APB-interfaced SPI Master IP core
into a synthesizable Register Transfer Level (RTL) description using Verilog
HDL.
4.1 Development Environment
The development and verification of this IP core utilized industry-standard
Electronic Design Automation (EDA) tools:

21
 HDL Language: Verilog HDL – Chosen for its widespread adoption in
digital design, strong community support, and extensive library of
synthesizable constructs.
 Simulation Tool: ModelSim SE 2020.4 (or similar tools like Xilinx
Vivado Simulator, Cadence Incisive/Xcelium, Synopsys VCS) – Used for
functional verification of the RTL design. Simulation allows for applying
test vectors, observing signal waveforms, and debugging logic errors
before synthesis.
 Synthesis Tool (for future steps): Xilinx Vivado 2023.2 (or Intel
Quartus Prime, Synopsys Design Compiler) – While not directly part of
the functional verification phase described in this report, this tool is
critical for converting the synthesizable Verilog RTL code into a gate-
level netlist, targeting a specific FPGA or ASIC technology. The design
principles adhered to throughout the RTL coding ensure synthesizability.
4.2 Module-Level RTL Code Explanation (Conceptual)
The modular architecture of the IP core is directly reflected in its Verilog RTL
implementation, with each functional block typically corresponding to a
separate Verilog module. This modularity enhances readability, reusability, and
eases the debugging process.
 apb_spi_master_top.v (Top-Level Module):
o This module serves as the primary wrapper for the entire IP core. It
instantiates all the sub-modules (e.g., apb_interface, spi_fsm,
baud_rate_gen, tx_fifo, rx_fifo) and defines the top-level
input/output ports (PCLK, PRESETn, APB signals, SPI signals).
o Its primary function is to establish the interconnections (using wire
declarations) between the ports of the instantiated sub-modules,
thereby defining the overall data flow and control paths within the
IP.
o HDL Constructs: Primarily uses module declaration, parameter
declarations for configurability, and assign statements for direct
wire connections.
 apb_interface.v:

22
o This module implements the APB slave logic. It contains a large
always @(posedge PCLK or negedge PRESETn) block that
manages the state of internal registers.
o Register Write Logic: Within the always block, if (PENABLE
&& PSEL && PWRITE) conditions, combined with case
statements on PADDR, are used to write PWDATA to the specific
internal control and data registers (e.g., spi_ctrl_reg_q,
spi_baud_div_reg_q).
o Register Read Logic: A combinatorial always @(*) block (or case
statement on PADDR) is used to drive PRDATA based on the
requested address and the current values of the internal registers
(spi_status_reg_q, spi_rx_data_reg_q, etc.). The PSLVERR signal
is also managed here, typically asserted if an unmapped PADDR is
detected during an active APB transaction.
o HDL Constructs: always @(posedge PCLK or negedge
PRESETn) for sequential logic (registers), always @(*) or assign
for combinatorial logic (address decoding, PRDATA multiplexing),
case statements for address-based selection.
 spi_fsm.v (SPI State Machine Module):
o This module contains the sequential logic for controlling the SPI
protocol.
o State Definition: An enum or local parameter declaration is used
to define the various states (e.g., IDLE, START_TRANSFER,
BIT_TRANSFER, END_TRANSFER).
o State Register: An always @(posedge PCLK or negedge
PRESETn) block manages the current_state and next_state
registers.
o Next State Logic: A combinatorial always @(*) block or case
statement evaluates the current_state and various inputs (e.g.,
tx_fifo_empty, bit_counter_zero, spi_enable_from_ctrl) to
determine the next_state.
o Output Logic: Another always @(*) or case statement on
current_state drives the SPI output signals (SCK, MOSI_data_out,

23
SS) and control signals for the FIFOs based on the configured
CPOL and CPHA values. For SCK generation, it typically controls
an enable signal for the Baud Rate Generator.
o Bit Counter: An internal counter tracks the number of bits
transferred per byte, usually decrementing from 7 to 0 (for 8-bit
MSB first).
o HDL Constructs: reg for state and data registers, wire for
interconnects, case statements for FSM logic, if-else for
conditional logic, posedge/negedge for clock/reset sensitivity.
 baud_rate_gen.v:
o This simple module implements the frequency divider.
o An always @(posedge PCLK or negedge PRESETn) block
contains a counter (clk_div_counter).
o When the counter reaches zero, the SCK output register is toggled
(sck_reg = ~sck_reg), and the counter is reloaded with the
BAUD_DIV value.
o HDL Constructs: reg for counter and clock output, if-else for reset
and counter logic.
 tx_fifo.v and rx_fifo.v:
o These modules implement the FIFO memory. They typically
employ a dual-port RAM model (either inferred or explicitly
instantiated).
o FIFO Pointers: read_ptr and write_ptr registers track the head and
tail of the FIFO.
o Full/Empty Logic: Combinatorial logic compares the read and
write pointers to generate full and empty flags.
o Read/Write Operations: An always @(posedge write_clk) block
handles data writes, incrementing write_ptr. An always @(posedge
read_clk) block handles data reads, incrementing read_ptr. Note
that for APB (PCLK) to SPI (SCK-derived) communication, these
FIFOs are often dual-clock FIFOs, requiring careful
synchronization logic for pointer comparisons across clock

24
domains. For simplicity, if the design allows, the write/read
requests to FIFO are synchronized to respective clocks.
o HDL Constructs: reg for memory array, pointers, full/empty flags;
always @(posedge clk) for sequential logic; if-else for pointer
wrap-around and read/write control.

Testbench Architecture
The testbench is a crucial component of the verification environment. It
provides the necessary stimulus to the Device Under Test (DUT) – our APB-
interfaced SPI Master IP core – and monitors its responses to ensure correct
behavior.:
 The central block labeled "APB-SPI Master IP Core (DUT)".
 "Clock & Reset Generator": A block providing PCLK and PRESETn
signals to the DUT and other testbench components.
 "APB Master Model / Driver": A block sending APB transaction
signals (PSEL, PENABLE, PWRITE, PADDR, PWDATA) to the DUT

25
and receiving PRDATA, PSLVERR from the DUT. This block typically
contains tasks or functions to simplify APB read/write sequences.
 "SPI Slave Model / Monitor": A block connected to the DUT's SPI pins
(SCK, MOSI, MISO, SS). This model acts as a behavioral SPI slave,
responding to the Master's commands. It also monitors the SPI signals to
verify protocol adherence and data correctness.
 "Stimulus Generator / Test Scenario Control": An overarching block
(often realized in the initial block of the top-level testbench) that
orchestrates the sequence of operations, calling tasks from the APB
Master Model and setting up specific test cases.
 "Scoreboard / Checker" (Optional but Recommended): A block that
receives data from both the APB Master Model (expected data) and the
SPI Slave Model (actual received data) and compares them to
automatically detect discrepancies.
 Arrows indicating signal flow between all components. Caption:
Architectural diagram of the verification environment for the APB-SPI
Master IP core. It illustrates the interaction between the Device Under
Test (DUT) and various testbench components, including bus models and
stimulus generation units.

Components of the Testbench:


1. Clock and Reset Generation: This fundamental component provides the
necessary clock (PCLK) and reset (PRESETn) signals to the DUT and
other synchronous components within the testbench. PCLK is typically a
high-frequency square wave, while PRESETn is asserted for a specific
duration at the beginning of the simulation to initialize the design.
2. APB Master Model / Driver: This component acts as the intelligent
counterpart to our APB Slave IP. It simulates the behavior of a CPU or a
system bus controller that would interact with the SPI Master. Its
responsibilities include:
o Generating valid APB read and write transactions.
o Driving the APB control (PSEL, PENABLE, PWRITE) and
address/data (PADDR, PWDATA) signals.
26
o Sampling the PRDATA and PSLVERR signals from the DUT
during read operations.
o The testbench utilizes Verilog task or function constructs to
encapsulate common APB transactions (e.g., apb_write, apb_read),
making the test sequences more readable and manageable.
3. SPI Slave Model / Monitor: This module is critical for verifying the SPI
communication itself. It simulates a compliant SPI Slave device that
communicates with the Master DUT.
o Slave Behavior: It responds to SS assertion, receives data on
MOSI from the Master, and drives data onto MISO for the Master
to receive. Its internal logic should mimic a real SPI slave, for
example, by echoing received data, sending a predefined sequence,
or responding to specific commands.
o Monitoring: Beyond just acting as a slave, this module also serves
as a monitor. It observes all SPI bus signals (SCK, MOSI, MISO,
SS) to verify that the Master DUT is generating correct waveforms
(e.g., correct SCK frequency, proper CPOL/CPHA timing) and that
the data transmitted (MOSI) adheres to expectations.
o $display statements within this model are often used to report
received data or protocol violations directly in the simulation
console.
4. Stimulus Generator / Test Scenario Control: This is typically an initial
block within the top-level testbench module that defines the sequence of
operations to be performed during the simulation. It involves calling the
APB Master Driver tasks in a specific order to:
o Apply initial reset.
o Configure the SPI Master IP (write to SPI_BAUD_DIV_REG,
SPI_MODE_CFG_REG, SPI_CTRL_REG).
o Initiate data transfers (write to SPI_TX_DATA_REG).
o Poll status registers (SPI_STATUS_REG) to check for completion
or error conditions.
o Read received data (SPI_RX_DATA_REG).

27
o Execute specific test scenarios (e.g., testing FIFO full/empty,
different SPI modes).

5.3 Test Scenarios


A comprehensive set of test scenarios was developed and executed to ensure the
functional correctness and robustness of the APB-interfaced SPI Master IP core.
 Basic Functionality Test:
o Objective: To verify fundamental data transmission and reception.
o Procedure: The SPI Master is configured for a standard SPI Mode
(e.g., Mode 0: CPOL=0, CPHA=0) and a specific baud rate. A
single 8-bit data byte (e.g., 8'hA5) is written to the
SPI_TX_DATA_REG. The simulation then waits for the BUSY

28
flag in SPI_STATUS_REG to clear, indicating transfer completion.
The SPI_RX_DATA_REG is then read.
o Expected Outcome: The SPI Slave Model reports receiving 8'hA5
on its MOSI input. The data read from SPI_RX_DATA_REG
matches the data the Slave Model was configured to transmit (e.g.,
8'h5A). The TX_EMPTY flag in SPI_STATUS_REG is set, and
BUSY is cleared.
 Multiple Byte Transfer Test:
o Objective: To verify the handling of sequential data transfers and
FIFO operation.
o Procedure: A sequence of multiple bytes (e.g., 8'h01, 8'h02, 8'h03)
is written consecutively to the SPI_TX_DATA_REG. The
testbench polls the BUSY flag to determine the end of the last
transfer. Subsequently, the SPI_RX_DATA_REG is read multiple
times to retrieve all received bytes.
o Expected Outcome: The SPI Slave Model logs the reception of all
transmitted bytes in the correct order. The Master IP's
SPI_RX_DATA_REG provides the corresponding received bytes in
the correct order.
 SPI Mode Configuration Test:
o Objective: To verify that the SPI Master correctly generates SCK,
drives MOSI, and samples MISO according to the selected CPOL
and CPHA settings for all four SPI modes.
o Procedure: The SPI_MODE_CFG_REG is written with values
corresponding to each of the four SPI modes (0, 1, 2, 3). For each
mode, a sample byte transfer is initiated.
o Expected Outcome: Simulation waveforms show SCK starting in
the correct idle state (CPOL), and MOSI data transitions and MISO
data sampling occurring on the correct SCK edges (CPHA).
 Baud Rate Configuration Test:
o Objective: To verify that the Baud Rate Generator correctly
produces SCK at the desired frequency.

29
o Procedure: Various BAUD_DIV values are written to the
SPI_BAUD_DIV_REG. A short transfer is initiated, or simply the
SCK signal is observed.
o Expected Outcome: The period of the SCK signal in the
simulation waveform precisely matches the period calculated using
the formula PCLK_Periodtimes(2times(BAUD_DIV+1)).
 FIFO Full/Empty Handling Test (Edge Cases):
o Objective: To verify robust behavior when FIFOs are pushed to
their limits.
o Procedure:
 TX FIFO Overrun: Attempt to write more bytes to
SPI_TX_DATA_REG than the FIFO's capacity without
allowing the SPI Master to transmit.
 RX FIFO Underrun: Attempt to read from
SPI_RX_DATA_REG when the RX FIFO is empty.
o Expected Outcome: The corresponding TX_OVERRUN or
RX_UNDERRUN flags in the SPI_STATUS_REG are asserted.
Subsequent reads of the status register clear these .
 Reset Behavior Test:
o Objective: To confirm that the IP core initializes correctly upon
reset and recovers gracefully from a reset assertion during an active
transaction.
o Procedure: The PRESETn signal is asserted (pulled low) for a few
PCLK cycles at the start of the simulation. Additionally, PRESETn
is asserted while an SPI transfer is in progress.
o Expected Outcome: Upon PRESETn assertion, all internal
registers return to their default values, state machines revert to the
IDLE state, and FIFOs are cleared. If reset during transfer, the
transfer is aborted, and the IP returns to a clean IDLE state after
reset de-assertion.

30
Output Waveforms
The following waveform screenshots, generated from the simulation tool,
visually demonstrate the correct functional behavior of the APB-interfaced SPI
Master IP core under various test scenarios. Each waveform includes the PCLK
signal as a timing reference.

31
32
SS transitions from high to low, initiating the transfer.
 SCK starts from a low state (CPOL=0).
 For CPHA=0:
o MOSI data should be observed to change on the falling edge of
SCK.
o MISO data should be sampled (and be stable) on the rising edge of
SCK.
 The waveform should clearly show 8 distinct clock cycles for an 8-bit
transfer. An example of 0xA5 being transmitted on MOSI and 0x5A being
received on MISO would be ideal, with individual bits identifiable.
 SS transitions from low to high after the last bit of the transaction,
indicating transfer completion. Caption: Detailed simulation waveform of
a complete 8-bit SPI data transfer in Mode 0 (CPOL=0, CPHA=0). The
waveform illustrates MOSI data (0xA5) changing on the SCK falling edge
and MISO data (0x5A) being sampled on the SCK rising edge, adhering
to the specified clock polarity and phase.

 PCLK with its known frequency (e.g., if PCLK is 100 MHz, its period is
10 ns).
 SCK as generated by the Baud Rate Generator. The waveform should
allow for easy measurement of the SCK period. For example, if
SPI_BAUD_DIV_REG was set to 9, the SCK period should be 200 ns
(corresponding to 5 MHz). The image should demonstrate that the
derived SCK frequency precisely matches the theoretical calculation
based on PCLK and the programmed BAUD_DIV value. Caption:
Simulation waveform demonstrating the relationship between the
Peripheral Clock (PCLK) and the generated SPI Clock (SCK). The
waveform confirms the Baud Rate Generator's correct operation by
showing SCK's frequency accurately matching the expected value derived
from the programmed divisor.

33
 PRESETn transitioning from high (inactive) to low (active) for a specific
duration, then returning high.
 During the PRESETn low period, all monitored internal state signals
should transition to their predefined reset values. For instance,
spi_fsm_state should revert to IDLE, spi_busy_flag should go to 0, and
tx_fifo_empty_flag should go to 1 (indicating an empty FIFO).
 After PRESETn goes high, these signals should remain in their reset state
until a valid APB transaction commands a change. If reset was asserted
during an active SPI transfer, the waveform should show the transfer
abruptly halting and the IP reverting to idle. Caption: Simulation
 waveform illustrating the synchronous reset behavior of the APB-SPI
Master IP core. The waveform confirms that all internal sequential
elements, including the SPI State Machine and status flags, are
correctly initialized to their default idle states upon the assertion of PRESETn.

34

You might also like