Serial Peripherals: SPI, I2C and Their Pins

You ask the flash chip for its name and read back nonsense. Then a sensor on a shared wire reads 0 after you let the wire go. Both times the question is the same: who drives this wire, and when?

You Will Be Able To

  • Say who makes the clock in SPI, and what chip select marks.
  • Explain why the answer to an SPI command arrives after the command write has completed.
  • Explain why a wire shared by several devices is pulled low or let go, and never driven high.
Lesson
S7.5
Time
26 min
Runs on
Your browser
Check
6 questions

The command write completes without error. The very next read returns nonsense. An hour later someone adds a wait loop, and the flash chip answers at once. What was the first read too early for?

Before You Start

You need Serial Peripherals: The UART: bits one after the other, and a bit time. You need GPIO: an output driver can be switched off, and the pin is then released.

SPI is short for Serial Peripheral Interface. I2C is short for Inter-Integrated Circuit. Both are taught in full in SPI in One Picture and I2C in One Picture. This page is about what they ask of a chip.

Five questions this page answers
Question
1Who makes the clock in SPI, and what does the other chip use it for?
2What does chip select tell the target?
3The command write has completed. Has the answer arrived?
4What is an open-drain driver, and what makes its wire high?
5Why must no device drive a shared wire high?

The Idea: Who Makes the Clock, and Who May Drive

A UART has no clock wire, so both ends must agree on the bit time in advance. That limits its speed. SPI spends one more wire: the sender of the clock sends the clock along. The other chip simply follows it.

The chip that makes the clock is the controller. The other is the target. The controller also drives a wire called chip select. It is low for the length of one exchange. It tells the target where a command starts and where it ends. Several targets can share clock and data wires if each has its own chip select.

Every SPI wire has one driver for ever. I2C makes the opposite choice. It has two wires, and every device on the board hangs on both. Any of them may speak. So no device may drive a wire high: another might be driving it low at the same moment.

Instead every I2C device has a driver that can only pull the wire low, or let it go. A resistor pulls the wire high when all have let go. Without this rule two chips would fight over the wire, and the level would belong to neither.

New Words

New words on this page
WordMeaning
Controller sideIn SPI, the chip that starts an exchange and makes its clock: the SPI controller. Older texts say master.
Target sideIn SPI, the chip that answers: the SPI target. It uses the clock it is given. Older texts say slave.
Serial clockThe clock wire of SPI. One bit moves each way on every period. It is usually called SCLK.
Chip selectA wire from the controller to one target. It is low for the whole of one exchange with that target.
Active lowA signal whose 0 means "on". Its name often ends in _n.
Push-pull driverAn output driver that can drive its wire to 1 and to 0.
Open-drain driverAn output driver that can pull its wire to 0 or let it go. It cannot drive a 1.
Pull-up resistorA resistor from a wire to the supply. It makes the wire 1 when no driver pulls it low.
The two registers of the SPI controller
OffsetNameWhat software does with it
0x00DATAWrites a command byte: the write starts an exchange of 32 serial clocks. Reads the last 24 bits received.
0x04STATUSReads bit 0, called BUSY. It is 1 while an exchange is on the wires.

The SPI controller is at base 0x10005000, on APB. Its data-out wire is called MOSI. Its data-in wire is called MISO. ap_soc has no I2C block.

One Picture: The Four Wires of SPI

SPI: Four Wires Between Two ChipsStep through the picture. It adds one wire at a time.
  • Peripheral
  • Clock / reset
  • Control / FSM
  • Bus
  • Memory
SPI: Four Wires Between Two ChipsStep through the picture. It adds one wire at a time. component SPI controller in ap_soc; it startsevery exchange component Serial clock made by thecontroller component Chip select low: "this exchange isfor you" component Data out controller to target component Data in target to controller component SPI target a flash chip on theboard drivestimes every bitdrivesframes the exchangeone bit each clockcommandone bit each clockanswer
  1. component SPI controllerin ap_soc; it starts every exchange
    • drives → Serial clock
    • drives → Chip select
    • one bit each clock → Data out
  2. component SPI targeta flash chip on the board
    • one bit each clock → Data in
  3. component Serial clockmade by the controller
    • times every bit → SPI target
  4. component Chip selectlow: "this exchange is for you"
    • frames the exchange → SPI target
  5. component Data outcontroller to target
    • command → SPI target
  6. component Data intarget to controller
    • answer → SPI controller
  1. Two chips

    The SPI controller sits in our chip. The SPI target is another chip on the board: here, a flash memory. The controller starts every exchange.

  2. The serial clock

    A UART has no clock wire. SPI has one. The controller makes the serial clock and sends it along, so the target needs no timing of its own.

  3. Chip select

    One more wire says when an exchange is on. The controller pulls chip select low at the start and lets it rise at the end. A target ignores the clock while its chip select is high.

  4. Data out

    On each serial clock the controller puts one bit on the data-out wire. The first eight bits are a command.

  5. Data in

    On each serial clock the target puts one bit on the data-in wire. So every clock moves one bit each way.

Read the diagram as text
  • SPI controller: in ap_soc; it starts every exchange
  • Serial clock: made by the controller
  • Chip select: low: "this exchange is for you"
  • Data out: controller to target
  • Data in: target to controller
  • SPI target: a flash chip on the board
  • SPI controller → Serial clock: drives
  • Serial clock → SPI target: times every bit
  • SPI controller → Chip select: drives
  • Chip select → SPI target: frames the exchange
  • SPI controller → Data out: one bit each clock
  • Data out → SPI target: command
  • SPI target → Data in: one bit each clock
  • Data in → SPI controller: answer

SPI between ap_soc and one flash chip. Each wire has one driver, and the driver never changes.

The Smallest Example, Worked by Hand

The controller asks a flash chip one question: "who are you?". The command for that is the byte 9f, which is 1001 1111. This flash chip answers with bytes that start with ef, which is 1110 1111. Take sixteen serial clocks, and the highest bit first.

Sixteen serial clocks, by hand
Serial clock1 to 89 to 16
Chip select00
Data out, from the controller1 0 0 1 1 1 1 10 0 0 0 0 0 0 0
Data in, from the targetnothing yet1 1 1 0 1 1 1 1
What it meansThe command 9fThe first byte of the answer, ef
One Exchange of Sixteen Clocks, by HandStep through the exchange of the hand table. Each column is one period of the serial clock.
0123456789101112131415clkchip selectdata outdata in
Scroll horizontally ↔
  1. Cycle 0

    Chip select is low. The first command bit, the highest, is on the data-out wire. The data-in wire carries nothing yet: it is drawn as 0.

  2. Cycle 7

    The eighth clock carries the last bit of the command 9f.

  3. Cycle 8

    From here the target answers. The controller sends zeros, only to keep the clock going.

  4. Cycle 15

    The last bit of the answer ef. After it chip select rises, and the exchange is over.

Drawn from the hand table, not recorded. The lab below runs 32 clocks: the same command and three bytes of answer.

Two things stand out. The answer comes after the command, on later clocks. And the controller keeps the clock running during the answer, with zeros on its own data wire. A target cannot send a bit without a clock from the controller.

Now time. In our controller one period of the serial clock is 4 system clocks. The real exchange has 32 serial clocks: the command and three bytes of answer. So chip select is low for 32 times 4, which is 128 system clocks. One register write is over in two or three.

The shared wire of I2C needs a different table. Two devices hang on one data wire with a pull-up resistor. Each can pull low or let go.

One wire, two open-drain drivers, by hand
Device ADevice BLevel of the wireWhy
lets golets go1Only the pull-up resistor acts.
pulls lowlets go0A pull to 0 beats the resistor.
lets gopulls low0A has let go, and the wire is still 0.
pulls lowpulls low0Both agree. Nobody fights.

Row 3 is the one that surprises. Device A sent a 1 by letting go, and the wire reads 0. To know the level, A must read the wire back. Its own output tells it nothing.

The Rules

  1. Rule 1: The SPI controller makes the serial clock.

    The target sends and takes bits only on that clock. With no clock, nothing moves.

  2. Rule 2: Chip select is low for the whole exchange.

    It falls before the first clock and rises after the last. A target whose chip select is high ignores the clock.

  3. Rule 3: Every serial clock moves one bit each way.

    The controller sends on its data-out wire while the target sends on the data-in wire.

  4. Rule 4: The write of the command only starts the exchange.

    BUSY is 1 until the last clock. The answer is in DATA after BUSY has fallen.

  5. Rule 5: An open-drain driver pulls low or lets go.

    A pull-up resistor makes the wire 1 when every driver has let go.

  6. Rule 6: A shared wire is 0 if any device pulls it low.

    So a device reads the wire back to learn its level. No device drives it high.

Sources for These Rules

SPI, its clock and its two data wires: Harris and Harris, Digital Design and Computer Architecture, ARM edition, chapter 9, section 9.3.4.1.

Open-drain outputs and pull-up resistors on the two wires of I2C: NXP UM10204, I2C-bus specification and user manual, revision 7, section 3.1.1.

The command 9f of this flash chip and its answer ef 40 18: Winbond W25Q128JV data sheet, revision F, sections 8.1.1 and 8.2.27.

Rule 4 and the numbers describe our own SPI controller. It runs 32 serial clocks for each exchange and 4 system clocks for each serial clock.

SPI has no single standard document. The data sheet of each target sets the order of the bits and the edge on which a bit is taken.

Now Run It

The lab at the end of this page has the SPI controller behind the bridge to APB. A model of the flash chip hangs on its four wires. Test code, a bus-functional model, stands in for the processor. The last five rows come from one wire with two open-drain drivers, as on I2C.

Printed by the lab on Icarus. The first five rows are SPI. The last five are the shared wire, named SDA as on I2C.
idle cs_n=1 sclk=0
started cs_n=0
finished cs_n=1 rises=32 low_clocks=128
spi period=4 system clocks
flash id=ef4018
idle SDA=1
both pull low SDA=0
host releases SDA=0
both release SDA=1
host drives high SDA=x

Rule 2 at work: chip select is 1 in "idle", 0 in "started" and 1 again in "finished". Rules 1 and 3 at work: rises=32 and low_clocks=128. One serial clock is 4 system clocks, as the next row says.

Rule 4 at work: the lab polls BUSY and only then reads DATA. It gets ef4018: the ef of the hand table, and two more bytes.

Rules 5 and 6 at work: with both drivers off, SDA is 1. In "host releases" the host has let go and SDA is still 0, because the target pulls. Only "both release" brings it back to 1.

This lab leaves things out. The flash chip is a model with ideal wires. The I2C part is one wire, with no clock wire, no addresses and no I2C block. The SPI controller has no interrupt request in this lab: software polls BUSY.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
SPI sends a clock wireEach end times the bits, as a UART doesNo baud rate to agree on, and much higher speed. One more pin.
One chip select for each targetAn address sent on the data wireA target needs no address logic. Each extra target costs the controller a pin.
SPI wires are push-pullOpen-drain wiresFast edges both ways. Only one driver may ever own each wire.
I2C wires are open-drainPush-pull with a rule for taking turnsMany devices share two pins, and a fight is impossible. The resistor makes rising edges slow.

The last row is why the pad of a pin matters to these devices. An SPI pin needs an ordinary output driver. An I2C pin needs a driver that only pulls low, and an input that reads the wire back at the same time.

The Trap: Reading Before the Answer, and Driving a One

Back to the nonsense. The driver wrote the command to DATA and read DATA in the next instruction. The write had completed, so the code looked right. But rule 4 says the write only starts the exchange. The read came long before the last bit of the answer.

The cure is the wait loop that was added an hour later: read STATUS until BUSY is 0, then read DATA. The exit check at the end of this page runs a look at STATUS at once, and another one much later.

The second trap is on the shared wire. A driver written for SPI sends a 1 by driving the wire high. Used on a shared wire, it meets a device that is pulling low. The last row of the lab shows the result: SDA=x.

In the simulator x means "two drivers disagree, so the level is unknown". On a board it means a large current between two chips, and a level somewhere in the middle. The driver must let go to send a 1, and read the wire back.

At Scale

This page1 target, 1 data wire each way
A boot flash4 data wires, tens of megabytes

This section looks ahead. The two buses of this page grow in different directions.

  1. Faster flash

    A boot flash uses four data wires at once to load code quickly. The Boot Flow shows what that code is for.

  2. Clock modes

    SPI targets differ in the resting level of the clock, and in the edge on which they take a bit. A controller has a setting for each.

  3. I2C in full

    A real I2C bus has a clock wire of the same open-drain kind. Every device has an address, and every byte is followed by an acknowledge bit.

  4. Pins

    Which pin carries which of these wires is a setting too. Pads and Pin Multiplexing is the next page.

Try It

Run the lab. The first five rows are one SPI exchange with the flash chip. The last five are one shared wire.

Put $display("poll busy=%b rises=%0d", result[0], rises); inside the loop that polls BUSY. Count the polls before BUSY falls.

In the last lines, set host_high=1 while target_low is 0. Predict the level of SDA before you run it.

Names Printed by the Lab
NameMeaning
cs_nChip select. The _n says that it is active low: 0 means selected.
sclkThe serial clock.
risesThe number of rising edges of the serial clock so far.
low_clocksThe number of system clocks for which chip select was low.
spi periodOne period of the serial clock, counted in system clocks.
flash idThe 24 bits that the controller received after the command, in hexadecimal.
SDAThe level of the shared data wire. x means that two drivers fight and the level is unknown.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: idle cs_n=1 sclk=0 started cs_n=0 finished cs_n=1 rises=32 low_clocks=128 spi period=4 system clocks flash id=ef4018 idle SDA=1 both pull low SDA=0 host releases SDA=0 both release SDA=1 host drives high SDA=x
Read included file: ahb_apb_bridge.sv
`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
  input  logic        hclk,
  input  logic        hresetn,
  input  logic        hsel,
  input  logic [31:0] haddr,
  input  logic [1:0]  htrans,
  input  logic        hwrite,
  input  logic [3:0]  hprot,
  input  logic [31:0] hwdata,
  input  logic [3:0]  hwstrb,
  input  logic        hready,
  output logic        hreadyout,
  output logic        hresp,
  output logic [31:0] hrdata,
  output logic        psel,
  output logic        penable,
  output logic        pwrite,
  output logic [31:0] paddr,
  output logic [31:0] pwdata,
  output logic [3:0]  pstrb,
  output logic [2:0]  pprot,
  input  logic        pready,
  input  logic [31:0] prdata,
  input  logic        pslverr);
  localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
  bit trace = 0;
  int st = IDLE;
  logic        wr = 0;
  logic [31:0] a = 0;
  logic [2:0]  prot = 0;
  wire take = hsel && hready && htrans[1];
  assign psel      = (st == SETUP || st == ACCESS);
  assign penable   = (st == ACCESS);
  assign pwrite    = wr;
  assign paddr     = {a[31:2], 2'b00};     // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
  assign pwdata    = wr ? hwdata : 32'h0;
  assign pstrb     = wr ? hwstrb : 4'h0;
  assign pprot     = prot;
  assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
  assign hresp     = (st == ERR1 || st == ERR2);
  assign hrdata    = (st == ACCESS) ? prdata : 32'h0;
  always @(posedge hclk or negedge hresetn) begin
    if (!hresetn) st <= IDLE;
    else begin
      case (st)
        SETUP:  st <= ACCESS;
        ACCESS: if (pready === 1'b1) begin
                  if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
                  st <= (pslverr === 1'b1) ? ERR1 : IDLE;
                end
        ERR1:   st <= ERR2;
        default: st <= IDLE;
      endcase
      // A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
      // or at the edge an access completes with OKAY.
      if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
        wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
      end
    end
  end
endmodule
Read included file: bus.svh
// One aligned word at a time, using the P4 bridge. Include inside tb.
logic hclk = 0, hresetn = 0, hwrite = 0;
logic [31:0] haddr = 0, hwdata = 0, result;
logic [1:0] htrans = 0;
wire hsel = haddr[31:16] == 16'h1000;
wire [31:0] hrdata, paddr, pwdata, prdata;
wire hready, hresp, psel, penable, pwrite;
bit trace_on = 0;

always #5 hclk = !hclk;

ahb_apb_bridge bridge(
  .hclk, .hresetn, .haddr, .hsel, .hwdata, .htrans, .hwrite,
  .hprot(4'b0011), .hwstrb(4'hf), .hready, .hreadyout(hready), .hresp, .hrdata,
  .paddr, .pwdata, .pwrite, .psel, .penable, .pready(1'b1), .prdata, .pslverr(1'b0)
);

always @(posedge hclk) begin
  if (trace_on)
    $display("bus req=%b sel=%b enable=%b ready=%b", htrans[1], psel, penable, hready);
end

task automatic access_word(input bit writing, input logic [31:0] address,
                           input logic [31:0] data, output logic [31:0] result);
  if (address[31:16] != 16'h1000 || address[1:0] != 0)
    $fatal(1, "This lab models aligned words in the APB window");
  @(negedge hclk);
  haddr = address;
  hwrite = writing;
  htrans = 2'b10;
  @(negedge hclk); // The address was accepted on the intervening rising edge.
  htrans = 0;
  haddr = 0;
  hwdata = data;
  do @(posedge hclk); while (!hready);
  if (hresp) $fatal(1, "Access failed at %08h", address);
  result = hrdata;
  #1;
endtask
Read included file: flash.sv
`timescale 1ns/1ns
module qspi_flash #(parameter PAGES=64, parameter time TPP=2000,TSE=4000,TBE1=6000,TBE2=8000,TCE=10000,TW=2000,TRES=100,TRST=100,
  TSUS=100,TVSL=200,TPUW=5000,TRESET=1000, parameter [63:0] UID=64'hd2_6b_15_0e_a7_3c_49_81)
 (input wire cs_n,clk,inout wire [3:0] io,output reg [3:0] oe=0);
 // Sparse full 24-bit address space: absent pages read FF. Capacity exhaustion is fatal,
 // never address truncation. Icarus 12 does not support associative arrays.
 reg [7:0] memory[0:PAGES*256-1]; int tags[0:PAGES-1]; int used=0;
 reg [3:0] out=0;
 for(genvar g=0;g<4;g++)begin:pad assign io[g]=oe[g]?out[g]:1'bz;end
 bit no_wel_check=0,no_page_wrap=0,busy_never_set=0,dummy_minus_one=0,wrap_ignored=0,mode_byte_stale=0,qe_ignored=0,drive_through_turnaround=0,erase_to_zero=0;
 bit wel=0,volatile_enable=0,busy=0,asleep=0,reset_enable=0,trace=0;
 // Fault twins for P7.11-P7.14 (QSPI_FAULTS_EXT); all 0 is the datasheet behaviour.
 bit cmp_ignored=0,lock_ignored=0,wp_ignored=0,suspend_restarts=0,suspend_ban_ignored=0,reset_keeps_volatile=0,lb_ignored=0,wake_on_any=0,no_tpuw=0;
 bit has_address=0,has_mode=0;string trace_address,trace_mode;
 reg [7:0] sr2=0,sr3=0,nv2=0,nv3=0,wrap_cfg=8'h10,wrap_in=8'h10;
 // Write protection (§7.1, §7.1.8-10): SR1 SRP SEC TB BP2-0, SR2 CMP LB3-1 QE SRL, SR3 WPS; the
 // individual locks (one per 64 KB block 1-254, one per 4 KB sector of blocks 0 and 255) power up set.
 reg [7:0] sr1=0,nv1=0,pending1;int pending_which=0;bit sus=0,lock_blk[0:255],lock_sec[0:31];
 // Security registers 1-3 at 001000h, 002000h, 003000h (§8.2.29-31); erased at the start.
 reg [7:0] secreg[0:767];
 // Hardware /RESET pin of the SOIC-16 and TFBGA parts (§4.6, §6.4); internal pull-up, so 1 when unused.
 bit reset_n=1;time reset_fell=0;
 // Power-up gate (§6.5, §9.3): power_cycle() starts it. Not powered by default: the bench starts ready.
 bit power_gate=0,blocked=0,wp_at_select=1;time powered_at=0;
 // In-flight operation, for suspend (§8.2.19-20) and for aborts by reset.
 int gen=0,cur_kind=0,susp_kind=0,susp_size=0;time cur_end=0,cur_time=0,susp_left=0,resumed_at=0;bit resumed=0;
 reg [23:0] susp_addr;reg [7:0] susp_buf[0:1023];bit susp_touched[0:1023];
 initial begin for(int i=0;i<256;i++)lock_blk[i]=1;for(int i=0;i<32;i++)lock_sec[i]=1;for(int i=0;i<768;i++)secreg[i]=8'hff;end
 localparam CMD=0,ADDR=1,MODE=2,DUMMY=3,WRITE=4,READ=5,WRAP=6,IGNORE=7;
 int state=IGNORE,got=0,width=1,data_width=1,dummies=0,clocks=0,output_bits=0,output_bytes=0,prog_count=0,status_count=0;
 reg [31:0] shift=0;reg [7:0] cmd=0,mode=8'hf0,status_in[0:1];reg [23:0] address=0,read_address=0;
 reg [7:0] pagebuf[0:1023];bit touched[0:1023];
 reg [7:0] pending2,pending3;bit pending_volatile;int pending_kind=0,erase_size=0;reg [23:0] pending_addr;
 time operation_time;
 function automatic [7:0] mem_read(input reg [23:0] a);
   mem_read=8'hff;for(int i=0;i<used;i++)if(tags[i]==(a>>8))mem_read=memory[i*256+a[7:0]];
 endfunction
 task automatic mem_write(input reg [23:0] a,input reg [7:0] v);
   int slot;slot=-1;for(int i=0;i<used;i++)if(tags[i]==(a>>8))slot=i;
   if(slot<0)begin if(used==PAGES)$fatal(1,"flash sparse capacity exceeded; raise PAGES");slot=used;used++;tags[slot]=a>>8;for(int j=0;j<256;j++)memory[slot*256+j]=8'hff;end
   memory[slot*256+a[7:0]]=v;
 endtask
 // §7.1.8: the range the BP bits name with CMP = 0, as [lo, hi). SEC = 1 with BP = 110 is not in the
 // table; the bench treats it like 10X (32 KB).
 function automatic int bp_size();
  int bp;bp=sr1[4:2];
  if(bp==0)bp_size=0;else if(bp==7)bp_size=16777216;
  else if(!sr1[6])bp_size=262144<<(bp-1);else bp_size=bp>=4?32768:4096<<(bp-1);
 endfunction
 function automatic bit lock_at(input reg [23:0] a);
  lock_at=(a[23:16]==0||a[23:16]==255)?lock_sec[(a[23:16]==255?16:0)+a[15:12]]:lock_blk[a[23:16]];
 endfunction
 // Is any byte of [a, a+n) protected? (§7.1.8 note 3: then the program or erase is ignored.)
 function automatic bit is_protected(input reg [23:0] a,input int n);
  int size,lo,hi;is_protected=0;
  if(sr3[2])begin if(!lock_ignored)for(int x=a;x<a+n;x+=4096)if(lock_at(x))is_protected=1;end
  else begin
   size=bp_size();lo=sr1[5]?0:16777216-size;hi=lo+size;
   if(!sr2[6]||cmp_ignored)is_protected=size>0&&a<hi&&a+n>lo;
   else is_protected=!(size>0&&a>=lo&&a+n<=hi);
  end
 endfunction
 function automatic bit secreg_ok(input reg [23:0] a);
  secreg_ok=a[23:16]==0&&a[11:8]==0&&a[15:12]>=1&&a[15:12]<=3;
 endfunction
 function automatic int secreg_index(input reg [23:0] a);secreg_index=(a[15:12]-1)*256+a[7:0];endfunction
 function automatic [7:0] read_value();
  case(cmd)
   8'h05:read_value={sr1[7:2],wel,(busy&&!busy_never_set)};
   8'h35:read_value={sus,sr2[6:0]};8'h15:read_value=sr3;
   8'h9f:case(output_bytes%3)0:read_value=8'hef;1:read_value=8'h40;default:read_value=8'h18;endcase
   8'h90,8'h92,8'h94:read_value=((output_bytes+address[0])%2)==0?8'hef:8'h17;
   8'h4b:read_value=UID>>(8*(7-output_bytes%8));
   8'h48:read_value=secreg_ok(read_address)?secreg[secreg_index(read_address)]:8'hff;
   8'h3d:read_value={7'b0,lock_at(address)};
   8'hab:read_value=8'h17;
   default:read_value=mem_read(read_address);
  endcase
 endfunction
 task automatic next_address();
  int n;n=8<<wrap_cfg[6:5];
  if(cmd==8'heb&&!wrap_cfg[4]&&!wrap_ignored)read_address=(read_address&~(n-1))|((read_address+1)&(n-1));
  else if(cmd==8'h48)read_address[7:0]=read_address[7:0]+1;
  else read_address=read_address+1;
 endtask
 task automatic decode_command();
   got=0;shift=0;width=1;data_width=1;dummies=0;
   blocked=!reset_n||(power_gate&&$time-powered_at<TVSL)
    ||(power_gate&&!no_tpuw&&$time-powered_at<TPUW&&(cmd==8'h06||cmd==8'h02||cmd==8'h32||cmd==8'h20||cmd==8'h52||cmd==8'hd8||cmd==8'hc7||cmd==8'h60||cmd==8'h01||cmd==8'h31||cmd==8'h11))
    ||(sus&&!suspend_ban_ignored&&susp_kind==2&&(cmd==8'h01||cmd==8'h20||cmd==8'h52||cmd==8'hd8||cmd==8'hc7||cmd==8'h60||cmd==8'h44))
    ||(sus&&!suspend_ban_ignored&&susp_kind==1&&(cmd==8'h01||cmd==8'h02||cmd==8'h32||cmd==8'h42));
   if(asleep&&wake_on_any)asleep=0;
   if((busy&&cmd!=8'h05&&cmd!=8'h35&&cmd!=8'h15)||(asleep&&cmd!=8'hab)||blocked)state=IGNORE;
   else case(cmd)
    8'h05,8'h35,8'h15,8'h9f:state=READ;
    8'h03,8'h0b,8'h3b,8'h6b,8'hbb,8'heb,8'h02,8'h32,8'h20,8'h52,8'hd8,8'h90,8'hab,
    8'h92,8'h94,8'h42,8'h44,8'h48,8'h36,8'h39,8'h3d:begin
      state=ADDR;width=(cmd==8'hbb||cmd==8'h92)?2:(cmd==8'heb||cmd==8'h94)?4:1;
      data_width=(cmd==8'h6b||cmd==8'heb||cmd==8'h32||cmd==8'h94)?4:(cmd==8'h3b||cmd==8'hbb||cmd==8'h92)?2:1;
      if((cmd==8'h6b||cmd==8'heb||cmd==8'h32||cmd==8'h94)&&!sr2[1]&&!qe_ignored)state=IGNORE;
    end
    8'h4b:begin state=DUMMY;dummies=32;end
    8'h77:begin state=sr2[1]||qe_ignored?DUMMY:IGNORE;dummies=6;width=4;end
    8'h01,8'h31,8'h11:begin state=WRITE;width=1;end
    default:state=IGNORE;
   endcase
 endtask
 always @(negedge cs_n)begin
   state=CMD;got=0;shift=0;cmd=0;clocks=0;output_bits=0;output_bytes=0;prog_count=0;status_count=0;width=1;oe=0;has_address=0;has_mode=0;blocked=0;
   if(!busy)for(int i=0;i<1024;i++)touched[i]=0;
 end
 always @(posedge clk)if(!cs_n)begin
  clocks++;
  if(state==CMD||state==ADDR||state==MODE||state==WRITE||state==WRAP)begin
   shift=(shift<<width)|({28'b0,io}&((1<<width)-1));got+=width;
   if(state==CMD&&got==8)begin cmd=shift[7:0];decode_command();end
   else if(state==ADDR&&got==24)begin
    address=shift[23:0];read_address=shift[23:0];has_address=1;got=0;shift=0;
    case(cmd)
     8'hbb,8'heb,8'h92,8'h94:state=MODE;
     8'h0b,8'h3b,8'h6b,8'h48:begin state=DUMMY;dummies=8-(dummy_minus_one?1:0);end
     8'h02,8'h32,8'h42:begin state=WRITE;width=data_width;end
     8'h20,8'h52,8'hd8,8'h44,8'h36,8'h39:state=IGNORE;
     default:state=READ;
    endcase
   end else if(state==MODE&&got==8)begin
     mode=shift[7:0];has_mode=1;got=0;shift=0;
     // Rev F figures 22a/24a require Fxh; other mode values are outside this model.
     if((mode&8'hf0)!=8'hf0||mode_byte_stale)state=IGNORE;
     else if(cmd==8'heb||cmd==8'h94)begin state=DUMMY;dummies=4-(dummy_minus_one?1:0);end else state=READ;
   end else if(state==WRAP&&got==8)begin wrap_in=shift[7:0];state=IGNORE;got=0;end
   else if(state==WRITE&&got==8)begin
     if(cmd==8'h02||cmd==8'h32||cmd==8'h42)begin
       if(no_page_wrap)begin if(address[7:0]+prog_count>=1024)$fatal(1,"program fixture too large");pagebuf[address[7:0]+prog_count]=shift[7:0];touched[address[7:0]+prog_count]=1;end
       else begin pagebuf[(address[7:0]+prog_count)%256]=shift[7:0];touched[(address[7:0]+prog_count)%256]=1;end
       prog_count++;
     end else begin if(status_count<2)status_in[status_count]=shift[7:0];status_count++;end
     got=0;shift=0;
   end
  end else if(state==DUMMY)begin
    dummies--;if(dummies==0)begin state=cmd==8'h77 ?WRAP:READ;got=0;shift=0;end
  end
 end
 always @(negedge clk)if(!cs_n)begin
  if(state==READ)begin
   oe=data_width==4?4'hf:data_width==2?4'h3:4'h2;
   if(data_width==1)out={2'b0,((read_value()>>(7-output_bits))&1'b1),1'b0};
   else out=(read_value()>>(8-data_width-output_bits))&((1<<data_width)-1);
   output_bits+=data_width;if(output_bits==8)begin output_bits=0;output_bytes++;next_address();end
  end else if(drive_through_turnaround&&(state==ADDR||state==MODE))begin oe=4'hf;out=0;end
  else oe=0;
 end
 always @(posedge cs_n)begin
  oe=0;
  if(trace&&clocks>=8)begin
   if(has_address)trace_address=$sformatf("%06h",address);else trace_address="------";
   if(has_mode)trace_mode=$sformatf("%02h",mode);else trace_mode="--";
   $display("QSPI %02h %s M %s C%0d B%0d",cmd,trace_address,trace_mode,clocks,output_bytes);
  end
  // Suspend is the one instruction besides the status reads that BUSY lets through (§7.1.1, §8.2.19).
  if(clocks==8&&cmd==8'h75&&!blocked&&!asleep)try_suspend();
  if(clocks==8&&cmd==8'h7a&&!blocked&&!asleep&&!busy&&sus)resume();
  if(!busy&&clocks>=8&&!blocked)begin
   if(cmd!=8'h66&&cmd!=8'h99)reset_enable=0;
   if(!asleep||cmd==8'hab)begin
    if(cmd==8'h77&&clocks==16&&(sr2[1]||qe_ignored))wrap_cfg=wrap_in;
    if(clocks==8)case(cmd)
     8'h06:wel=1;8'h04:wel=0;8'h50:volatile_enable=1;8'hb9:asleep=1;
     8'h66:reset_enable=1;
     8'h7e,8'h98:if(wel)for(int i=0;i<256;i++)begin lock_blk[i]=cmd==8'h7e;if(i<32)lock_sec[i]=cmd==8'h7e;end
     8'h99:if(reset_enable)begin pending_kind=4;operation_time=TRST;busy=1;start_op();reset_enable=0;end
     default:;
    endcase
    // tRES1/tRES2 apply only when ABh releases power-down (§8.2.22); an ID read while awake needs no wait.
    if(cmd==8'hab&&asleep)begin asleep=0;pending_kind=5;operation_time=TRES;busy=1;start_op();end
    if((cmd==8'h02||cmd==8'h32)&&(wel||no_wel_check)&&prog_count>0&&got==0&&state==WRITE
      &&!is_protected({address[23:8],8'h0},256)&&!in_suspended({address[23:8],8'h0},256))begin pending_kind=1;pending_addr={address[23:8],8'h0};operation_time=TPP;busy=1;start_op();end
    if((wel||no_wel_check)&&((clocks==32&&(cmd==8'h20||cmd==8'h52||cmd==8'hd8))||(clocks==8&&(cmd==8'hc7||cmd==8'h60))))begin
     erase_size=cmd==8'h20 ?4096:cmd==8'h52 ?32768:cmd==8'hd8 ?65536:16777216;
     pending_addr=address&~(erase_size-1);
     if(!is_protected(pending_addr,erase_size)&&!in_suspended(pending_addr,erase_size))begin
      pending_kind=2;operation_time=cmd==8'h20 ?TSE:cmd==8'h52 ?TBE1:cmd==8'hd8 ?TBE2:TCE;busy=1;start_op();
     end
    end
    // Security registers (§8.2.29, §8.2.30): WEL, a valid register address, its LB bit clear.
    if(cmd==8'h42&&wel&&prog_count>0&&got==0&&state==WRITE&&secreg_ok(address)&&(!sr2[2+address[13:12]]||lb_ignored))begin
     pending_kind=6;pending_addr={address[23:8],8'h0};operation_time=TPP;busy=1;start_op();
    end
    if(cmd==8'h44&&wel&&clocks==32&&secreg_ok(address)&&(!sr2[2+address[13:12]]||lb_ignored))begin
     pending_kind=7;pending_addr={address[23:8],8'h0};operation_time=TSE;busy=1;start_op();
    end
    // Individual locks (§8.2.32, §8.2.33): WEL, then the address. §7.1.2 does not list them among the
    // instructions that clear WEL, so the bench leaves WEL set.
    if((cmd==8'h36||cmd==8'h39)&&wel&&clocks==32)begin
     if(address[23:16]==0||address[23:16]==255)lock_sec[(address[23:16]==255?16:0)+address[15:12]]=cmd==8'h36;
     else lock_blk[address[23:16]]=cmd==8'h36;
    end
    // Write Status (§8.2.5): SRL = 1 locks it; SRP = 1 with /WP low locks it in Standard/Dual SPI
    // (§7.1.1 table, §4.3). /WP is IO2, read at CS falling and rising. Writable bits only; LB3-1 and
    // SRL never go from 1 to 0. Each register's non-volatile copy changes only when it is written.
    if((cmd==8'h01||cmd==8'h31||cmd==8'h11)&&(wel||volatile_enable)&&got==0&&(status_count==1||(cmd==8'h01&&status_count==2))
      &&!sr2[0]&&!(sr1[7]&&!sr2[1]&&!wp_ignored&&(wp_at_select===1'b0||io[2]===1'b0)))begin
     pending1=sr1;pending2=sr2;pending3=sr3;pending_which=0;
     if(cmd==8'h01)begin pending1=(sr1&8'h03)|(status_in[0]&8'hfc);pending_which=1;end
     if(cmd==8'h31)begin pending2=status_in[0];pending_which|=2;end
     if(cmd==8'h01&&status_count==2)begin pending2=status_in[1];pending_which|=2;end
     if(pending_which&2)pending2=(sr2&8'h84)|(pending2&8'h7b)|(sr2&8'h39);
     if(cmd==8'h11)begin pending3=(sr3&8'h9b)|(status_in[0]&8'h64);pending_which=4;end
     pending_volatile=volatile_enable;pending_kind=3;operation_time=volatile_enable?1:TW;
     if(!volatile_enable)busy=1;start_op();volatile_enable=0;
    end
   end
  end
 end
 always @(negedge cs_n)wp_at_select=io[2]!==1'b0;
 // One process per internal operation. Suspend, reset and power cycles bump gen, so an aborted
 // operation's process ends without completing.
 task start_op();cur_kind=pending_kind;cur_end=$time+operation_time;cur_time=operation_time;fork run_op(gen,operation_time,pending_kind);join_none endtask
 task automatic run_op(input int g,input time t,input int kind);
  #(t);
  if(g==gen)begin
   case(kind)
    1:for(int i=0;i<1024;i++)if(touched[i])mem_write(pending_addr+i,mem_read(pending_addr+i)&pagebuf[i]);
    2:for(int p=0;p<used;p++)if(((tags[p]<<8)&~(erase_size-1))==pending_addr)for(int j=0;j<256;j++)memory[p*256+j]=erase_to_zero?8'h00:8'hff;
    3:begin sr1=pending1;sr2=pending2;sr3=pending3;
       if(!pending_volatile)begin if(pending_which&1)nv1=sr1;if(pending_which&2)nv2=sr2;if(pending_which&4)nv3=sr3;end end
    4:volatile_reset();
    6:for(int i=0;i<256;i++)if(touched[i])secreg[secreg_index(pending_addr)+i]&=pagebuf[i];
    7:for(int i=0;i<256;i++)secreg[secreg_index(pending_addr)+i]=8'hff;
    default:;
   endcase
   if(kind!=5&&kind!=8&&!(kind==3&&pending_volatile))wel=0;
   busy=0;cur_kind=0;
  end
 endtask
 // Software reset, /RESET and power-up all return the volatile state to its power-on values (§8.2.37).
 task automatic volatile_reset();
  if(!reset_keeps_volatile)begin sr1=nv1;sr2=nv2;sr3=nv3;end wel=0;volatile_enable=0;wrap_cfg=8'h10;asleep=0;
  sus=0;susp_kind=0;resumed=0;for(int i=0;i<256;i++)lock_blk[i]=1;for(int i=0;i<32;i++)lock_sec[i]=1;
 endtask
 function automatic bit in_suspended(input reg [23:0] a,input int n);
  int lo,size;size=susp_kind==1?256:susp_size;lo=susp_addr;
  in_suspended=sus&&a<lo+size&&a+n>lo;
 endfunction
 // §8.2.19: only a sector or block erase, or a page program, can be suspended; SUS must be 0 and BUSY 1.
 // A suspend sooner than TSUS after a resume breaks the datasheet's rule; the bench ignores it.
 task automatic try_suspend();
  if(!sus&&busy&&(cur_kind==1||(cur_kind==2&&erase_size<16777216))&&!(resumed&&$time-resumed_at<TSUS))begin
   gen++;susp_left=suspend_restarts?cur_time:cur_end-$time;susp_kind=cur_kind;susp_addr=pending_addr;susp_size=erase_size;
   for(int i=0;i<1024;i++)begin susp_buf[i]=pagebuf[i];susp_touched[i]=touched[i];end
   sus=1;pending_kind=8;operation_time=TSUS;start_op();
  end
 endtask
 // §8.2.20: SUS clears at once, BUSY sets, the operation finishes the time it had left.
 task automatic resume();
  sus=0;resumed=1;resumed_at=$time;pending_addr=susp_addr;erase_size=susp_size;
  for(int i=0;i<1024;i++)begin pagebuf[i]=susp_buf[i];touched[i]=susp_touched[i];end
  pending_kind=susp_kind;operation_time=susp_left;susp_kind=0;busy=1;start_op();
 endtask
 // /RESET held low at least TRESET (§4.6, §6.4) ends any operation and resets the device; while it is
 // low, frames are ignored. A shorter pulse is ignored (the datasheet only recommends the minimum).
 always @(negedge reset_n)reset_fell=$time;
 always @(posedge reset_n)if($time-reset_fell>=TRESET)begin gen++;busy=0;cur_kind=0;reset_enable=0;volatile_reset();end
 // Power-up (§6.5, §9.3): reset state, then no instruction until TVSL and no write until TPUW. SRL
 // returns to 0 (§7.1.1 note 1); suspended work is lost (§8.2.19).
 task automatic power_cycle();
  gen++;busy=0;cur_kind=0;reset_enable=0;nv2[0]=0;volatile_reset();power_gate=1;powered_at=$time;
 endtask
endmodule
Read included file: serial.sv
// APB teaching slice. Aligned word transfers, no waits, one system clock.
// UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
module serial_slice(
  input wire clk, reset_n, sel, enable, wr,
  input wire [31:0] addr, wdata,
  output logic [31:0] rdata,
  input wire rx_done, input wire [7:0] rx_data,
  output wire tx, irq, dma_req, cs_n, mosi,
  output logic sclk, input wire miso
);
  // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
  // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
  localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
             SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
  wire access = sel && enable;
  logic [7:0] fifo [0:1];
  logic head, tail;
  logic [1:0] used;
  wire pop = access && !wr && addr == UART_RXDATA && used != 0;
  wire push = rx_done && (used < 2 || pop);
  assign irq = used != 0;
  assign dma_req = used == 2;
  logic [9:0] frame;
  logic [3:0] bits_left, tick;
  assign tx = frame[0];

  logic [31:0] shift;
  logic [23:0] flash_id;
  logic [5:0] clocks_left;
  logic half_tick;
  assign cs_n = clocks_left == 0;
  assign mosi = shift[31];
  always_comb begin
    case (addr)
      UART_RXDATA: rdata = irq ? fifo[head] : 0;
      UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
      SPI_DATA:    rdata = {8'b0, flash_id};
      SPI_STATUS:  rdata = {31'b0, !cs_n};
      default:     rdata = 0;
    endcase
  end
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      used <= 0;
      head <= 0;
      tail <= 0;
      frame <= '1;
      bits_left <= 0;
      tick <= 0;
      clocks_left <= 0;
      half_tick <= 0;
      sclk <= 0;
      shift <= 0;
      flash_id <= 0;
    end else begin
      if (push) begin
        fifo[tail] <= rx_data;
        tail <= !tail;
      end
      if (pop) head <= !head;
      case ({push,pop})
        2'b10: used <= used + 1'b1;
        2'b01: used <= used - 1'b1;
        default: ;
      endcase

      if (bits_left != 0) begin
        tick <= tick + 1'b1;
        if (tick == 15) begin
          frame <= {1'b1, frame[9:1]};
          bits_left <= bits_left - 1'b1;
        end
      end else if (access && wr && addr == UART_TXDATA) begin
        frame <= {1'b1, wdata[7:0], 1'b0};
        bits_left <= 10;
        tick <= 0;
      end

      if (cs_n) begin
        if (access && wr && addr == SPI_DATA) begin
          shift <= {wdata[7:0], 24'b0};
          clocks_left <= 32;
          half_tick <= 0;
        end
      end else begin
        half_tick <= !half_tick;
        if (half_tick) begin
          sclk <= !sclk;
          if (!sclk) flash_id <= {flash_id[22:0], miso};
          else begin
            shift <= shift << 1;
            clocks_left <= clocks_left - 1'b1;
          end
        end
      end
    end
  end
endmodule

Check Yourself

Predict the outputIn this run software looks at STATUS just after the command write, and again 200 clocks later. What is the last row the lab prints?
`timescale 1ns/1ns
module tb;
  `include "bus.svh"
  localparam DATA=32'h10005000, STATUS=32'h10005004;   // registers of the SPI controller
  wire cs_n, sclk, mosi;            // chip select (active low), serial clock, data out of the controller
  wire miso;                        // data into the controller
  tri [3:0] io;                     // the four data pins of the flash chip; this lab uses two
  assign io[0]=mosi;
  assign io[3:2]=2'b11;
  assign miso=io[1];
  qspi_flash flash(.cs_n,.clk(sclk),.io);
  serial_slice device(.clk(hclk),.reset_n(hresetn),.sel(psel),.enable(penable),
    .wr(pwrite),.addr(paddr),.wdata(pwdata),.rdata(prdata),.rx_done(1'b0),
    .rx_data(8'b0),.tx(),.irq(),.dma_req(),.cs_n,.sclk,.mosi,.miso);
  int system_edges=0, last_rise=0, full_period=0, rises=0, low_clocks=0;
  always @(posedge hclk) begin
    system_edges++;
    if (!cs_n) low_clocks++;        // clocks for which chip select is low
  end
  always @(posedge sclk) begin
    full_period=system_edges-last_rise;
    last_rise=system_edges;
    rises++;                        // rising edges of the serial clock
  end
  initial begin
    repeat (2) @(negedge hclk);
    hresetn=1;
    access_word(1, DATA, 32'h9f, result);       // write the command
    access_word(0, STATUS, 0, result);          // look at once
    $display("at once busy=%b cs_n=%b rises=%0d", result[0], cs_n, rises);
    repeat (200) @(negedge hclk);               // do something else for 200 clocks
    access_word(0, STATUS, 0, result);
    $display("later busy=%b cs_n=%b rises=%0d", result[0], cs_n, rises);
    $finish;
  end
  initial #100000 $fatal(1,"Transaction timed out");
endmodule
Read included file: ahb_apb_bridge.sv
`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
  input  logic        hclk,
  input  logic        hresetn,
  input  logic        hsel,
  input  logic [31:0] haddr,
  input  logic [1:0]  htrans,
  input  logic        hwrite,
  input  logic [3:0]  hprot,
  input  logic [31:0] hwdata,
  input  logic [3:0]  hwstrb,
  input  logic        hready,
  output logic        hreadyout,
  output logic        hresp,
  output logic [31:0] hrdata,
  output logic        psel,
  output logic        penable,
  output logic        pwrite,
  output logic [31:0] paddr,
  output logic [31:0] pwdata,
  output logic [3:0]  pstrb,
  output logic [2:0]  pprot,
  input  logic        pready,
  input  logic [31:0] prdata,
  input  logic        pslverr);
  localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
  bit trace = 0;
  int st = IDLE;
  logic        wr = 0;
  logic [31:0] a = 0;
  logic [2:0]  prot = 0;
  wire take = hsel && hready && htrans[1];
  assign psel      = (st == SETUP || st == ACCESS);
  assign penable   = (st == ACCESS);
  assign pwrite    = wr;
  assign paddr     = {a[31:2], 2'b00};     // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
  assign pwdata    = wr ? hwdata : 32'h0;
  assign pstrb     = wr ? hwstrb : 4'h0;
  assign pprot     = prot;
  assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
  assign hresp     = (st == ERR1 || st == ERR2);
  assign hrdata    = (st == ACCESS) ? prdata : 32'h0;
  always @(posedge hclk or negedge hresetn) begin
    if (!hresetn) st <= IDLE;
    else begin
      case (st)
        SETUP:  st <= ACCESS;
        ACCESS: if (pready === 1'b1) begin
                  if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
                  st <= (pslverr === 1'b1) ? ERR1 : IDLE;
                end
        ERR1:   st <= ERR2;
        default: st <= IDLE;
      endcase
      // A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
      // or at the edge an access completes with OKAY.
      if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
        wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
      end
    end
  end
endmodule
Read included file: bus.svh
// One aligned word at a time, using the P4 bridge. Include inside tb.
logic hclk = 0, hresetn = 0, hwrite = 0;
logic [31:0] haddr = 0, hwdata = 0, result;
logic [1:0] htrans = 0;
wire hsel = haddr[31:16] == 16'h1000;
wire [31:0] hrdata, paddr, pwdata, prdata;
wire hready, hresp, psel, penable, pwrite;
bit trace_on = 0;

always #5 hclk = !hclk;

ahb_apb_bridge bridge(
  .hclk, .hresetn, .haddr, .hsel, .hwdata, .htrans, .hwrite,
  .hprot(4'b0011), .hwstrb(4'hf), .hready, .hreadyout(hready), .hresp, .hrdata,
  .paddr, .pwdata, .pwrite, .psel, .penable, .pready(1'b1), .prdata, .pslverr(1'b0)
);

always @(posedge hclk) begin
  if (trace_on)
    $display("bus req=%b sel=%b enable=%b ready=%b", htrans[1], psel, penable, hready);
end

task automatic access_word(input bit writing, input logic [31:0] address,
                           input logic [31:0] data, output logic [31:0] result);
  if (address[31:16] != 16'h1000 || address[1:0] != 0)
    $fatal(1, "This lab models aligned words in the APB window");
  @(negedge hclk);
  haddr = address;
  hwrite = writing;
  htrans = 2'b10;
  @(negedge hclk); // The address was accepted on the intervening rising edge.
  htrans = 0;
  haddr = 0;
  hwdata = data;
  do @(posedge hclk); while (!hready);
  if (hresp) $fatal(1, "Access failed at %08h", address);
  result = hrdata;
  #1;
endtask
Read included file: flash.sv
`timescale 1ns/1ns
module qspi_flash #(parameter PAGES=64, parameter time TPP=2000,TSE=4000,TBE1=6000,TBE2=8000,TCE=10000,TW=2000,TRES=100,TRST=100,
  TSUS=100,TVSL=200,TPUW=5000,TRESET=1000, parameter [63:0] UID=64'hd2_6b_15_0e_a7_3c_49_81)
 (input wire cs_n,clk,inout wire [3:0] io,output reg [3:0] oe=0);
 // Sparse full 24-bit address space: absent pages read FF. Capacity exhaustion is fatal,
 // never address truncation. Icarus 12 does not support associative arrays.
 reg [7:0] memory[0:PAGES*256-1]; int tags[0:PAGES-1]; int used=0;
 reg [3:0] out=0;
 for(genvar g=0;g<4;g++)begin:pad assign io[g]=oe[g]?out[g]:1'bz;end
 bit no_wel_check=0,no_page_wrap=0,busy_never_set=0,dummy_minus_one=0,wrap_ignored=0,mode_byte_stale=0,qe_ignored=0,drive_through_turnaround=0,erase_to_zero=0;
 bit wel=0,volatile_enable=0,busy=0,asleep=0,reset_enable=0,trace=0;
 // Fault twins for P7.11-P7.14 (QSPI_FAULTS_EXT); all 0 is the datasheet behaviour.
 bit cmp_ignored=0,lock_ignored=0,wp_ignored=0,suspend_restarts=0,suspend_ban_ignored=0,reset_keeps_volatile=0,lb_ignored=0,wake_on_any=0,no_tpuw=0;
 bit has_address=0,has_mode=0;string trace_address,trace_mode;
 reg [7:0] sr2=0,sr3=0,nv2=0,nv3=0,wrap_cfg=8'h10,wrap_in=8'h10;
 // Write protection (§7.1, §7.1.8-10): SR1 SRP SEC TB BP2-0, SR2 CMP LB3-1 QE SRL, SR3 WPS; the
 // individual locks (one per 64 KB block 1-254, one per 4 KB sector of blocks 0 and 255) power up set.
 reg [7:0] sr1=0,nv1=0,pending1;int pending_which=0;bit sus=0,lock_blk[0:255],lock_sec[0:31];
 // Security registers 1-3 at 001000h, 002000h, 003000h (§8.2.29-31); erased at the start.
 reg [7:0] secreg[0:767];
 // Hardware /RESET pin of the SOIC-16 and TFBGA parts (§4.6, §6.4); internal pull-up, so 1 when unused.
 bit reset_n=1;time reset_fell=0;
 // Power-up gate (§6.5, §9.3): power_cycle() starts it. Not powered by default: the bench starts ready.
 bit power_gate=0,blocked=0,wp_at_select=1;time powered_at=0;
 // In-flight operation, for suspend (§8.2.19-20) and for aborts by reset.
 int gen=0,cur_kind=0,susp_kind=0,susp_size=0;time cur_end=0,cur_time=0,susp_left=0,resumed_at=0;bit resumed=0;
 reg [23:0] susp_addr;reg [7:0] susp_buf[0:1023];bit susp_touched[0:1023];
 initial begin for(int i=0;i<256;i++)lock_blk[i]=1;for(int i=0;i<32;i++)lock_sec[i]=1;for(int i=0;i<768;i++)secreg[i]=8'hff;end
 localparam CMD=0,ADDR=1,MODE=2,DUMMY=3,WRITE=4,READ=5,WRAP=6,IGNORE=7;
 int state=IGNORE,got=0,width=1,data_width=1,dummies=0,clocks=0,output_bits=0,output_bytes=0,prog_count=0,status_count=0;
 reg [31:0] shift=0;reg [7:0] cmd=0,mode=8'hf0,status_in[0:1];reg [23:0] address=0,read_address=0;
 reg [7:0] pagebuf[0:1023];bit touched[0:1023];
 reg [7:0] pending2,pending3;bit pending_volatile;int pending_kind=0,erase_size=0;reg [23:0] pending_addr;
 time operation_time;
 function automatic [7:0] mem_read(input reg [23:0] a);
   mem_read=8'hff;for(int i=0;i<used;i++)if(tags[i]==(a>>8))mem_read=memory[i*256+a[7:0]];
 endfunction
 task automatic mem_write(input reg [23:0] a,input reg [7:0] v);
   int slot;slot=-1;for(int i=0;i<used;i++)if(tags[i]==(a>>8))slot=i;
   if(slot<0)begin if(used==PAGES)$fatal(1,"flash sparse capacity exceeded; raise PAGES");slot=used;used++;tags[slot]=a>>8;for(int j=0;j<256;j++)memory[slot*256+j]=8'hff;end
   memory[slot*256+a[7:0]]=v;
 endtask
 // §7.1.8: the range the BP bits name with CMP = 0, as [lo, hi). SEC = 1 with BP = 110 is not in the
 // table; the bench treats it like 10X (32 KB).
 function automatic int bp_size();
  int bp;bp=sr1[4:2];
  if(bp==0)bp_size=0;else if(bp==7)bp_size=16777216;
  else if(!sr1[6])bp_size=262144<<(bp-1);else bp_size=bp>=4?32768:4096<<(bp-1);
 endfunction
 function automatic bit lock_at(input reg [23:0] a);
  lock_at=(a[23:16]==0||a[23:16]==255)?lock_sec[(a[23:16]==255?16:0)+a[15:12]]:lock_blk[a[23:16]];
 endfunction
 // Is any byte of [a, a+n) protected? (§7.1.8 note 3: then the program or erase is ignored.)
 function automatic bit is_protected(input reg [23:0] a,input int n);
  int size,lo,hi;is_protected=0;
  if(sr3[2])begin if(!lock_ignored)for(int x=a;x<a+n;x+=4096)if(lock_at(x))is_protected=1;end
  else begin
   size=bp_size();lo=sr1[5]?0:16777216-size;hi=lo+size;
   if(!sr2[6]||cmp_ignored)is_protected=size>0&&a<hi&&a+n>lo;
   else is_protected=!(size>0&&a>=lo&&a+n<=hi);
  end
 endfunction
 function automatic bit secreg_ok(input reg [23:0] a);
  secreg_ok=a[23:16]==0&&a[11:8]==0&&a[15:12]>=1&&a[15:12]<=3;
 endfunction
 function automatic int secreg_index(input reg [23:0] a);secreg_index=(a[15:12]-1)*256+a[7:0];endfunction
 function automatic [7:0] read_value();
  case(cmd)
   8'h05:read_value={sr1[7:2],wel,(busy&&!busy_never_set)};
   8'h35:read_value={sus,sr2[6:0]};8'h15:read_value=sr3;
   8'h9f:case(output_bytes%3)0:read_value=8'hef;1:read_value=8'h40;default:read_value=8'h18;endcase
   8'h90,8'h92,8'h94:read_value=((output_bytes+address[0])%2)==0?8'hef:8'h17;
   8'h4b:read_value=UID>>(8*(7-output_bytes%8));
   8'h48:read_value=secreg_ok(read_address)?secreg[secreg_index(read_address)]:8'hff;
   8'h3d:read_value={7'b0,lock_at(address)};
   8'hab:read_value=8'h17;
   default:read_value=mem_read(read_address);
  endcase
 endfunction
 task automatic next_address();
  int n;n=8<<wrap_cfg[6:5];
  if(cmd==8'heb&&!wrap_cfg[4]&&!wrap_ignored)read_address=(read_address&~(n-1))|((read_address+1)&(n-1));
  else if(cmd==8'h48)read_address[7:0]=read_address[7:0]+1;
  else read_address=read_address+1;
 endtask
 task automatic decode_command();
   got=0;shift=0;width=1;data_width=1;dummies=0;
   blocked=!reset_n||(power_gate&&$time-powered_at<TVSL)
    ||(power_gate&&!no_tpuw&&$time-powered_at<TPUW&&(cmd==8'h06||cmd==8'h02||cmd==8'h32||cmd==8'h20||cmd==8'h52||cmd==8'hd8||cmd==8'hc7||cmd==8'h60||cmd==8'h01||cmd==8'h31||cmd==8'h11))
    ||(sus&&!suspend_ban_ignored&&susp_kind==2&&(cmd==8'h01||cmd==8'h20||cmd==8'h52||cmd==8'hd8||cmd==8'hc7||cmd==8'h60||cmd==8'h44))
    ||(sus&&!suspend_ban_ignored&&susp_kind==1&&(cmd==8'h01||cmd==8'h02||cmd==8'h32||cmd==8'h42));
   if(asleep&&wake_on_any)asleep=0;
   if((busy&&cmd!=8'h05&&cmd!=8'h35&&cmd!=8'h15)||(asleep&&cmd!=8'hab)||blocked)state=IGNORE;
   else case(cmd)
    8'h05,8'h35,8'h15,8'h9f:state=READ;
    8'h03,8'h0b,8'h3b,8'h6b,8'hbb,8'heb,8'h02,8'h32,8'h20,8'h52,8'hd8,8'h90,8'hab,
    8'h92,8'h94,8'h42,8'h44,8'h48,8'h36,8'h39,8'h3d:begin
      state=ADDR;width=(cmd==8'hbb||cmd==8'h92)?2:(cmd==8'heb||cmd==8'h94)?4:1;
      data_width=(cmd==8'h6b||cmd==8'heb||cmd==8'h32||cmd==8'h94)?4:(cmd==8'h3b||cmd==8'hbb||cmd==8'h92)?2:1;
      if((cmd==8'h6b||cmd==8'heb||cmd==8'h32||cmd==8'h94)&&!sr2[1]&&!qe_ignored)state=IGNORE;
    end
    8'h4b:begin state=DUMMY;dummies=32;end
    8'h77:begin state=sr2[1]||qe_ignored?DUMMY:IGNORE;dummies=6;width=4;end
    8'h01,8'h31,8'h11:begin state=WRITE;width=1;end
    default:state=IGNORE;
   endcase
 endtask
 always @(negedge cs_n)begin
   state=CMD;got=0;shift=0;cmd=0;clocks=0;output_bits=0;output_bytes=0;prog_count=0;status_count=0;width=1;oe=0;has_address=0;has_mode=0;blocked=0;
   if(!busy)for(int i=0;i<1024;i++)touched[i]=0;
 end
 always @(posedge clk)if(!cs_n)begin
  clocks++;
  if(state==CMD||state==ADDR||state==MODE||state==WRITE||state==WRAP)begin
   shift=(shift<<width)|({28'b0,io}&((1<<width)-1));got+=width;
   if(state==CMD&&got==8)begin cmd=shift[7:0];decode_command();end
   else if(state==ADDR&&got==24)begin
    address=shift[23:0];read_address=shift[23:0];has_address=1;got=0;shift=0;
    case(cmd)
     8'hbb,8'heb,8'h92,8'h94:state=MODE;
     8'h0b,8'h3b,8'h6b,8'h48:begin state=DUMMY;dummies=8-(dummy_minus_one?1:0);end
     8'h02,8'h32,8'h42:begin state=WRITE;width=data_width;end
     8'h20,8'h52,8'hd8,8'h44,8'h36,8'h39:state=IGNORE;
     default:state=READ;
    endcase
   end else if(state==MODE&&got==8)begin
     mode=shift[7:0];has_mode=1;got=0;shift=0;
     // Rev F figures 22a/24a require Fxh; other mode values are outside this model.
     if((mode&8'hf0)!=8'hf0||mode_byte_stale)state=IGNORE;
     else if(cmd==8'heb||cmd==8'h94)begin state=DUMMY;dummies=4-(dummy_minus_one?1:0);end else state=READ;
   end else if(state==WRAP&&got==8)begin wrap_in=shift[7:0];state=IGNORE;got=0;end
   else if(state==WRITE&&got==8)begin
     if(cmd==8'h02||cmd==8'h32||cmd==8'h42)begin
       if(no_page_wrap)begin if(address[7:0]+prog_count>=1024)$fatal(1,"program fixture too large");pagebuf[address[7:0]+prog_count]=shift[7:0];touched[address[7:0]+prog_count]=1;end
       else begin pagebuf[(address[7:0]+prog_count)%256]=shift[7:0];touched[(address[7:0]+prog_count)%256]=1;end
       prog_count++;
     end else begin if(status_count<2)status_in[status_count]=shift[7:0];status_count++;end
     got=0;shift=0;
   end
  end else if(state==DUMMY)begin
    dummies--;if(dummies==0)begin state=cmd==8'h77 ?WRAP:READ;got=0;shift=0;end
  end
 end
 always @(negedge clk)if(!cs_n)begin
  if(state==READ)begin
   oe=data_width==4?4'hf:data_width==2?4'h3:4'h2;
   if(data_width==1)out={2'b0,((read_value()>>(7-output_bits))&1'b1),1'b0};
   else out=(read_value()>>(8-data_width-output_bits))&((1<<data_width)-1);
   output_bits+=data_width;if(output_bits==8)begin output_bits=0;output_bytes++;next_address();end
  end else if(drive_through_turnaround&&(state==ADDR||state==MODE))begin oe=4'hf;out=0;end
  else oe=0;
 end
 always @(posedge cs_n)begin
  oe=0;
  if(trace&&clocks>=8)begin
   if(has_address)trace_address=$sformatf("%06h",address);else trace_address="------";
   if(has_mode)trace_mode=$sformatf("%02h",mode);else trace_mode="--";
   $display("QSPI %02h %s M %s C%0d B%0d",cmd,trace_address,trace_mode,clocks,output_bytes);
  end
  // Suspend is the one instruction besides the status reads that BUSY lets through (§7.1.1, §8.2.19).
  if(clocks==8&&cmd==8'h75&&!blocked&&!asleep)try_suspend();
  if(clocks==8&&cmd==8'h7a&&!blocked&&!asleep&&!busy&&sus)resume();
  if(!busy&&clocks>=8&&!blocked)begin
   if(cmd!=8'h66&&cmd!=8'h99)reset_enable=0;
   if(!asleep||cmd==8'hab)begin
    if(cmd==8'h77&&clocks==16&&(sr2[1]||qe_ignored))wrap_cfg=wrap_in;
    if(clocks==8)case(cmd)
     8'h06:wel=1;8'h04:wel=0;8'h50:volatile_enable=1;8'hb9:asleep=1;
     8'h66:reset_enable=1;
     8'h7e,8'h98:if(wel)for(int i=0;i<256;i++)begin lock_blk[i]=cmd==8'h7e;if(i<32)lock_sec[i]=cmd==8'h7e;end
     8'h99:if(reset_enable)begin pending_kind=4;operation_time=TRST;busy=1;start_op();reset_enable=0;end
     default:;
    endcase
    // tRES1/tRES2 apply only when ABh releases power-down (§8.2.22); an ID read while awake needs no wait.
    if(cmd==8'hab&&asleep)begin asleep=0;pending_kind=5;operation_time=TRES;busy=1;start_op();end
    if((cmd==8'h02||cmd==8'h32)&&(wel||no_wel_check)&&prog_count>0&&got==0&&state==WRITE
      &&!is_protected({address[23:8],8'h0},256)&&!in_suspended({address[23:8],8'h0},256))begin pending_kind=1;pending_addr={address[23:8],8'h0};operation_time=TPP;busy=1;start_op();end
    if((wel||no_wel_check)&&((clocks==32&&(cmd==8'h20||cmd==8'h52||cmd==8'hd8))||(clocks==8&&(cmd==8'hc7||cmd==8'h60))))begin
     erase_size=cmd==8'h20 ?4096:cmd==8'h52 ?32768:cmd==8'hd8 ?65536:16777216;
     pending_addr=address&~(erase_size-1);
     if(!is_protected(pending_addr,erase_size)&&!in_suspended(pending_addr,erase_size))begin
      pending_kind=2;operation_time=cmd==8'h20 ?TSE:cmd==8'h52 ?TBE1:cmd==8'hd8 ?TBE2:TCE;busy=1;start_op();
     end
    end
    // Security registers (§8.2.29, §8.2.30): WEL, a valid register address, its LB bit clear.
    if(cmd==8'h42&&wel&&prog_count>0&&got==0&&state==WRITE&&secreg_ok(address)&&(!sr2[2+address[13:12]]||lb_ignored))begin
     pending_kind=6;pending_addr={address[23:8],8'h0};operation_time=TPP;busy=1;start_op();
    end
    if(cmd==8'h44&&wel&&clocks==32&&secreg_ok(address)&&(!sr2[2+address[13:12]]||lb_ignored))begin
     pending_kind=7;pending_addr={address[23:8],8'h0};operation_time=TSE;busy=1;start_op();
    end
    // Individual locks (§8.2.32, §8.2.33): WEL, then the address. §7.1.2 does not list them among the
    // instructions that clear WEL, so the bench leaves WEL set.
    if((cmd==8'h36||cmd==8'h39)&&wel&&clocks==32)begin
     if(address[23:16]==0||address[23:16]==255)lock_sec[(address[23:16]==255?16:0)+address[15:12]]=cmd==8'h36;
     else lock_blk[address[23:16]]=cmd==8'h36;
    end
    // Write Status (§8.2.5): SRL = 1 locks it; SRP = 1 with /WP low locks it in Standard/Dual SPI
    // (§7.1.1 table, §4.3). /WP is IO2, read at CS falling and rising. Writable bits only; LB3-1 and
    // SRL never go from 1 to 0. Each register's non-volatile copy changes only when it is written.
    if((cmd==8'h01||cmd==8'h31||cmd==8'h11)&&(wel||volatile_enable)&&got==0&&(status_count==1||(cmd==8'h01&&status_count==2))
      &&!sr2[0]&&!(sr1[7]&&!sr2[1]&&!wp_ignored&&(wp_at_select===1'b0||io[2]===1'b0)))begin
     pending1=sr1;pending2=sr2;pending3=sr3;pending_which=0;
     if(cmd==8'h01)begin pending1=(sr1&8'h03)|(status_in[0]&8'hfc);pending_which=1;end
     if(cmd==8'h31)begin pending2=status_in[0];pending_which|=2;end
     if(cmd==8'h01&&status_count==2)begin pending2=status_in[1];pending_which|=2;end
     if(pending_which&2)pending2=(sr2&8'h84)|(pending2&8'h7b)|(sr2&8'h39);
     if(cmd==8'h11)begin pending3=(sr3&8'h9b)|(status_in[0]&8'h64);pending_which=4;end
     pending_volatile=volatile_enable;pending_kind=3;operation_time=volatile_enable?1:TW;
     if(!volatile_enable)busy=1;start_op();volatile_enable=0;
    end
   end
  end
 end
 always @(negedge cs_n)wp_at_select=io[2]!==1'b0;
 // One process per internal operation. Suspend, reset and power cycles bump gen, so an aborted
 // operation's process ends without completing.
 task start_op();cur_kind=pending_kind;cur_end=$time+operation_time;cur_time=operation_time;fork run_op(gen,operation_time,pending_kind);join_none endtask
 task automatic run_op(input int g,input time t,input int kind);
  #(t);
  if(g==gen)begin
   case(kind)
    1:for(int i=0;i<1024;i++)if(touched[i])mem_write(pending_addr+i,mem_read(pending_addr+i)&pagebuf[i]);
    2:for(int p=0;p<used;p++)if(((tags[p]<<8)&~(erase_size-1))==pending_addr)for(int j=0;j<256;j++)memory[p*256+j]=erase_to_zero?8'h00:8'hff;
    3:begin sr1=pending1;sr2=pending2;sr3=pending3;
       if(!pending_volatile)begin if(pending_which&1)nv1=sr1;if(pending_which&2)nv2=sr2;if(pending_which&4)nv3=sr3;end end
    4:volatile_reset();
    6:for(int i=0;i<256;i++)if(touched[i])secreg[secreg_index(pending_addr)+i]&=pagebuf[i];
    7:for(int i=0;i<256;i++)secreg[secreg_index(pending_addr)+i]=8'hff;
    default:;
   endcase
   if(kind!=5&&kind!=8&&!(kind==3&&pending_volatile))wel=0;
   busy=0;cur_kind=0;
  end
 endtask
 // Software reset, /RESET and power-up all return the volatile state to its power-on values (§8.2.37).
 task automatic volatile_reset();
  if(!reset_keeps_volatile)begin sr1=nv1;sr2=nv2;sr3=nv3;end wel=0;volatile_enable=0;wrap_cfg=8'h10;asleep=0;
  sus=0;susp_kind=0;resumed=0;for(int i=0;i<256;i++)lock_blk[i]=1;for(int i=0;i<32;i++)lock_sec[i]=1;
 endtask
 function automatic bit in_suspended(input reg [23:0] a,input int n);
  int lo,size;size=susp_kind==1?256:susp_size;lo=susp_addr;
  in_suspended=sus&&a<lo+size&&a+n>lo;
 endfunction
 // §8.2.19: only a sector or block erase, or a page program, can be suspended; SUS must be 0 and BUSY 1.
 // A suspend sooner than TSUS after a resume breaks the datasheet's rule; the bench ignores it.
 task automatic try_suspend();
  if(!sus&&busy&&(cur_kind==1||(cur_kind==2&&erase_size<16777216))&&!(resumed&&$time-resumed_at<TSUS))begin
   gen++;susp_left=suspend_restarts?cur_time:cur_end-$time;susp_kind=cur_kind;susp_addr=pending_addr;susp_size=erase_size;
   for(int i=0;i<1024;i++)begin susp_buf[i]=pagebuf[i];susp_touched[i]=touched[i];end
   sus=1;pending_kind=8;operation_time=TSUS;start_op();
  end
 endtask
 // §8.2.20: SUS clears at once, BUSY sets, the operation finishes the time it had left.
 task automatic resume();
  sus=0;resumed=1;resumed_at=$time;pending_addr=susp_addr;erase_size=susp_size;
  for(int i=0;i<1024;i++)begin pagebuf[i]=susp_buf[i];touched[i]=susp_touched[i];end
  pending_kind=susp_kind;operation_time=susp_left;susp_kind=0;busy=1;start_op();
 endtask
 // /RESET held low at least TRESET (§4.6, §6.4) ends any operation and resets the device; while it is
 // low, frames are ignored. A shorter pulse is ignored (the datasheet only recommends the minimum).
 always @(negedge reset_n)reset_fell=$time;
 always @(posedge reset_n)if($time-reset_fell>=TRESET)begin gen++;busy=0;cur_kind=0;reset_enable=0;volatile_reset();end
 // Power-up (§6.5, §9.3): reset state, then no instruction until TVSL and no write until TPUW. SRL
 // returns to 0 (§7.1.1 note 1); suspended work is lost (§8.2.19).
 task automatic power_cycle();
  gen++;busy=0;cur_kind=0;reset_enable=0;nv2[0]=0;volatile_reset();power_gate=1;powered_at=$time;
 endtask
endmodule
Read included file: serial.sv
// APB teaching slice. Aligned word transfers, no waits, one system clock.
// UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
module serial_slice(
  input wire clk, reset_n, sel, enable, wr,
  input wire [31:0] addr, wdata,
  output logic [31:0] rdata,
  input wire rx_done, input wire [7:0] rx_data,
  output wire tx, irq, dma_req, cs_n, mosi,
  output logic sclk, input wire miso
);
  // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
  // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
  localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
             SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
  wire access = sel && enable;
  logic [7:0] fifo [0:1];
  logic head, tail;
  logic [1:0] used;
  wire pop = access && !wr && addr == UART_RXDATA && used != 0;
  wire push = rx_done && (used < 2 || pop);
  assign irq = used != 0;
  assign dma_req = used == 2;
  logic [9:0] frame;
  logic [3:0] bits_left, tick;
  assign tx = frame[0];

  logic [31:0] shift;
  logic [23:0] flash_id;
  logic [5:0] clocks_left;
  logic half_tick;
  assign cs_n = clocks_left == 0;
  assign mosi = shift[31];
  always_comb begin
    case (addr)
      UART_RXDATA: rdata = irq ? fifo[head] : 0;
      UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
      SPI_DATA:    rdata = {8'b0, flash_id};
      SPI_STATUS:  rdata = {31'b0, !cs_n};
      default:     rdata = 0;
    endcase
  end
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      used <= 0;
      head <= 0;
      tail <= 0;
      frame <= '1;
      bits_left <= 0;
      tick <= 0;
      clocks_left <= 0;
      half_tick <= 0;
      sclk <= 0;
      shift <= 0;
      flash_id <= 0;
    end else begin
      if (push) begin
        fifo[tail] <= rx_data;
        tail <= !tail;
      end
      if (pop) head <= !head;
      case ({push,pop})
        2'b10: used <= used + 1'b1;
        2'b01: used <= used - 1'b1;
        default: ;
      endcase

      if (bits_left != 0) begin
        tick <= tick + 1'b1;
        if (tick == 15) begin
          frame <= {1'b1, frame[9:1]};
          bits_left <= bits_left - 1'b1;
        end
      end else if (access && wr && addr == UART_TXDATA) begin
        frame <= {1'b1, wdata[7:0], 1'b0};
        bits_left <= 10;
        tick <= 0;
      end

      if (cs_n) begin
        if (access && wr && addr == SPI_DATA) begin
          shift <= {wdata[7:0], 24'b0};
          clocks_left <= 32;
          half_tick <= 0;
        end
      end else begin
        half_tick <= !half_tick;
        if (half_tick) begin
          sclk <= !sclk;
          if (!sclk) flash_id <= {flash_id[22:0], miso};
          else begin
            shift <= shift << 1;
            clocks_left <= clocks_left - 1'b1;
          end
        end
      end
    end
  end
endmodule
ConceptWho makes the serial clock of SPI?
ConceptWhat does a low chip select tell an SPI target?
ConceptThe write of a command to DATA has completed. Where is the answer?
ConceptWhat makes a wire with open-drain drivers read 1?
ConceptWhy must no device drive a shared wire high?

Common Mistakes

Wrong Read the answer as soon as the command write has completed.

The write only starts the exchange. The bits take many clocks.

Fix Wait until BUSY is 0, then read DATA.

Wrong Count half a period as the serial clock.

One period is a rise and a fall: two toggles.

Fix Count from one rising edge to the next.

Wrong Drive a shared wire high to send a 1.

Another device may be pulling it low at the same time.

Fix Let the wire go, and read its level back.

Remember

  • In SPI the controller makes the serial clock, and chip select is low for the whole exchange.
  • Every serial clock moves one bit each way. The answer comes on later clocks than the command.
  • The write of a command only starts the exchange. Wait for BUSY to fall before you read the answer.
  • A shared wire has open-drain drivers and a pull-up resistor: it is 0 if anyone pulls, and nobody drives it high.

Practice

Report a problem with this page