Serial Peripherals: The UART, Its Queue and Its Requests

You type K on a new board and wait for the echo. One letter comes in on one wire, waits in a queue, and asks to be read. Then a third letter arrives too soon.

You Will Be Able To

  • Explain how one wire carries a byte with no clock wire beside it, and work out the length of a frame.
  • Say what the receive queue is for, and which byte a read returns.
  • Define a watermark, and read the interrupt request and the DMA request from the number of bytes that wait.
Lesson
S7.3
Time
26 min
Runs on
Your browser
Check
6 questions

A terminal pastes three letters into a new board. Two echo back, and the third is gone with no error bit set. Where did the letter go?

Before You Start

You need The Anatomy of a Peripheral: registers, core logic, an interrupt request and a DMA request. You need S0.4 for one APB read.

The bits on the wire are taught in full in Serial Links in One Picture. This page needs only the short form below.

Five questions this page answers
Question
1How does one wire carry a byte when no clock wire comes with it?
2What does the bit time depend on, and how long is one frame?
3What is the receive queue for, and which byte does a read return?
4What is a watermark, and why do the two requests have different ones?
5A byte arrives while the queue is full. What happens to it?

The Idea: A Byte on One Wire, a Queue, and a Call for Service

A console needs only two wires: one into the chip and one out. A byte has eight bits, so the bits go one after the other. That is what serial means. The device that does it is a UART, a universal asynchronous receiver and transmitter.

Asynchronous means that no clock wire travels with the data. The two ends agree in advance how long one bit lasts. The sender marks the start of each byte by pulling the wire low. The receiver then counts time on its own clock and takes the bits.

Bytes arrive when the outside world sends them, not when software is ready. So the UART keeps finished bytes in a small queue. Software reads them later, oldest first. Without a queue, the second byte would overwrite the first.

Somebody must still empty the queue in time. The UART counts the bytes that wait and compares the count with a set level, called a watermark. At or above the watermark it raises a request. A low watermark calls for help early. A high one calls late, and moves more bytes for each call.

New Words

New words on this page
WordMeaning
UARTUniversal asynchronous receiver and transmitter: a device that sends and receives bytes one bit at a time, with no clock wire.
Start bitA bit of 0 that the sender puts in front of each byte. It tells the receiver that a byte begins.
Stop bitA bit of 1 that the sender puts after each byte. The wire then rests at 1 until the next start bit.
Serial frameOne byte as it travels on the wire: a start bit, the data bits, a stop bit.
Bit timeHow long one bit stays on the wire.
Baud rateThe number of bits sent in one second. It is 1 divided by the bit time.
Receive queueA small store that holds received bytes in the order they came. Engineers call it a FIFO: first in, first out.
WatermarkA set number of waiting bytes. A request is raised when the queue holds that many or more.
OverrunA byte that arrives while the receive queue is full. It has nowhere to go.
The registers of UART0 that this page uses
OffsetNameWhat software does with it
0x00TXDATAWrites a byte to send.
0x04STATUSReads three bits. Bit 0: room to transmit. Bit 1: a received byte waits. Bit 2: the receive queue is full.
0x0CRXDATAReads the oldest received byte. The read removes it from the queue.

UART0 is at base 0x10000000, on APB. One more register, at 0x08, enables the "room to transmit" interrupt. The lesson on drivers uses it.

One Picture: From the Wire to the Read

UART0, from the Wire to the ReadStep through the picture. It follows one received byte, and then one sent byte.
  • Pads
  • Peripheral
  • Memory
  • Bus
  • Processor
UART0, From the Wire to the ReadStep through the picture. It follows one received byte, and then one sent byte. component RX wire one bit at a time, infrom the board component Receiver times the bits,gathers a byte component Receive queue two bytes, oldestfirst component Registers RXDATA, TXDATA,STATUS component Requests interrupt and DMA component Transmitter sends one byte, bit bybit component TX wire out to the board bitsa finished bytethe oldest bytehow many bytes waita byte to sendbits
  1. component RX wireone bit at a time, in from the board
    • bits → Receiver
  2. component Receivertimes the bits, gathers a byte
    • a finished byte → Receive queue
  3. component Receive queuetwo bytes, oldest first
    • the oldest byte → Registers
    • how many bytes wait → Requests
  4. component RegistersRXDATA, TXDATA, STATUS
    • a byte to send → Transmitter
  5. component Requestsinterrupt and DMA
  6. component Transmittersends one byte, bit by bit
    • bits → TX wire
  7. component TX wireout to the board
  1. One wire

    A byte arrives on the RX wire one bit at a time. No clock wire comes with it.

  2. The receiver

    The receiver waits for the wire to fall. From that moment it counts its own clock, and takes one bit in each bit time.

  3. The queue

    A finished byte goes into the receive queue. It waits there until someone reads it. The next byte can arrive meanwhile.

  4. The read

    A read of the register RXDATA returns the oldest byte and removes it from the queue.

  5. The requests

    UART0 watches how many bytes wait. One byte is enough for the interrupt request. Two raise the DMA request as well.

  6. The way out

    A write to the register TXDATA hands one byte to the transmitter. It sends the bits on the TX wire, timed by the same count.

Read the diagram as text
  • RX wire: one bit at a time, in from the board
  • Receiver: times the bits, gathers a byte
  • Receive queue: two bytes, oldest first
  • Registers: RXDATA, TXDATA, STATUS
  • Requests: interrupt and DMA
  • Transmitter: sends one byte, bit by bit
  • TX wire: out to the board
  • RX wire → Receiver: bits
  • Receiver → Receive queue: a finished byte
  • Receive queue → Registers: the oldest byte
  • Receive queue → Requests: how many bytes wait
  • Registers → Transmitter: a byte to send
  • Transmitter → TX wire: bits

UART0 of ap_soc as this page builds it. The queue of two bytes is a teaching size: a real one holds 16 or more.

The Smallest Example, Worked by Hand

Send the letter K. Its code is 4b in hexadecimal, which is 0100 1011 in binary. The frame has ten bits: a start bit, the eight data bits with the lowest bit first, and a stop bit.

The frame of K, bit by bit
Bit time12345678910
What it isstartbit 0bit 1bit 2bit 3bit 4bit 5bit 6bit 7stop
Level on the wire0110100101

Read the data bits from right to left and you get 0100 1011 again. In this UART one bit time is 16 clocks. So the frame lasts 10 times 16, which is 160 clocks. During that time the transmitter has no room for another byte.

Now the queue. It holds two bytes. The interrupt watermark is 1, and the DMA watermark is 2. Two letters arrive, K and then a question mark, and software reads twice.

Two bytes in, two bytes out, by hand
StepWhat happensQueue, oldest firstBytes waitingInterrupt requestDMA request
1K arrives.K110
2A question mark arrives.K, ?211
3Software reads RXDATA and gets K.?110
4Software reads RXDATA and gets the question mark.empty000

Step 3 is the one to study. The read returned K, the oldest byte. The DMA request fell, because one byte is below its watermark of 2. The interrupt request stayed, because one byte is still at its watermark of 1.

The Rules

  1. Rule 1: A frame is a start bit, eight data bits and a stop bit.

    The start bit is 0 and the stop bit is 1. The lowest data bit goes first. Between frames the wire rests at 1.

  2. Rule 2: Each end times the bits on its own clock.

    One bit time is a count of clocks: 16 in this UART. Both ends must reach the same bit time.

  3. Rule 3: A read of RXDATA returns the oldest byte and removes it.

    The read counts on the access edge. A byte that has been read is gone from the queue.

  4. Rule 4: A request is 1 while the queue holds its watermark or more.

    The interrupt watermark is 1 byte. The DMA watermark is 2 bytes, which is a full queue here.

  5. Rule 5: A request carries no data.

    It says that bytes wait. The bytes stay in the queue until a read of RXDATA takes them.

  6. Rule 6: A byte that arrives at a full queue is lost.

    This UART drops the new byte and keeps the two old ones. It sets no error bit.

Sources for These Rules

The serial frame, the baud rate, and interrupts from a UART: Harris and Harris, Digital Design and Computer Architecture, ARM edition, chapter 9, sections 9.3.4.2 and 9.3.7.

The edge on which a register read counts: Arm AMBA APB Protocol Specification, IHI 0024 issue E, sections 3.1 and 4.1.

Rule 1 is the common frame of eight data bits, no parity bit and one stop bit. Other frames exist: see the serial lessons of the Protocols track.

Rules 2 to 6 describe our own UART0. The 16 clocks, the queue of two bytes, both watermarks and the silent loss are our own choices for the lab.

A real UART reports an overrun in a status bit. Ours does not, and the trap below shows what that costs.

Now Run It

The lab at the end of this page is UART0 behind the bridge to APB. Test code, a bus-functional model, stands in for the processor. It also plays the terminal: it sends K and a question mark into RX, and it rebuilds what comes out of TX.

Printed by the lab on Icarus. In "status" the left bit is "queue full", the middle bit "a byte waits", the right bit "room to transmit".
idle status=001 irq=0 dma=0
one byte status=011 irq=1 dma=0
two bytes status=111 irq=1 dma=1
bus req=1 sel=0 enable=0 ready=1
bus req=0 sel=1 enable=0 ready=0
bus req=0 sel=1 enable=1 ready=1
read byte=4b
after read status=011 irq=1 dma=0
sending status=010 irq=1 dma=0
terminal received=K
sent status=011 irq=1 dma=0
tx bits=0110100101
frame=160 clocks

Rule 4 at work: after one byte the row has status=011, irq=1 and dma=0. After two bytes it has status=111 and dma=1. Rule 3 at work: the read returns 4b, the K, and not the question mark.

Rule 5 at work: in "after read" irq is still 1 and dma is 0. One byte waits. The three rows that start with "bus" are the edges of that read. The byte left the queue at the last of them, where enable is 1.

Rule 1 at work: the row "tx bits" reads 0110100101. That is the hand table: start, the bits of K with the lowest first, stop. Rule 2 at work: frame=160 clocks. In "sending" the right bit of status is 0: no room while the frame is on the wire.

This lab leaves things out. The bits on RX are lined up with the clock of the chip: a real receiver samples each bit several times. There is no parity bit and no error bit. The interrupt request goes nowhere, and no DMA block is in the lab.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
No clock wireA clock wire beside the dataTwo wires make a console. Both ends must agree on the baud rate, and their clocks must be close.
A queue for received bytesOne register for the last byteSoftware may be late by the depth of the queue. A queue costs storage and a counter.
A low watermark for the interruptInterrupt only when the queue is fullSoftware learns of the first byte at once. It is called once for every byte or two.
A higher watermark for DMAThe same watermark for bothThe DMA block moves several bytes for one request. Less room is left when the request rises.

The Trap: The Third Letter

Back to the three pasted letters. The lab below sends K, a question mark and an exclamation mark, with no read in between. Then software reads three times.

The same UART0 in a second run. Three bytes arrive before the first read.
two bytes status=111 irq=1 dma=1
three sent status=111 irq=1 dma=1
first read byte=4b
second read byte=3f
after two reads status=001 irq=0 dma=0
third read byte=00

After two bytes the queue is full and both requests are 1. The third byte arrives, and nothing changes: the status is 111 before and after. The reads return 4b and 3f, the K and the question mark. The third read returns 00, because the queue is empty.

Rule 6 took the exclamation mark. Look at when the DMA request rose: with the second byte, at a full queue. From that moment there was no free place. Whoever served that request had less than one frame, 160 clocks, to read a byte.

So a watermark is also a deadline. The room that is left when the request rises, times the time of one frame, is how long service may take. A deeper queue with the same watermark buys time. A higher watermark in the same queue spends it.

At Scale

This pagea queue of 2 bytes
A common UARTqueues of 16 to 64 bytes each way

This section looks ahead. A real UART is this page with a deeper queue and more settings.

  1. A baud divider register

    The count of clocks for one bit time is a register, so that one design serves many clocks and baud rates. The worksheet below works such counts out.

  2. Watermarks as settings

    Software picks each watermark for its own delays. A transmit queue has one too: "call me when few bytes are left to send".

  3. Error bits

    A real UART reports overrun, a missing stop bit and a wrong parity bit in its status register. Errors, break and recovery covers them.

  4. The other serial devices

    I2C, the Inter-Integrated Circuit bus, and SPI come next: Serial Peripherals: SPI, I2C and Their Pins. To build a UART with queues as hardware, see the UART capstone.

Try It

Run the lab. Follow the three bits of status from "idle" to "sent".

Change send("K") to send("U"). The code of U is 55. Predict the row "tx bits" before you run it.

Move the line send("?"); and the status line after it to just below status("after read"). Predict every status row.

Names Printed by the Lab
NameMeaning
statusThe three low bits of the register STATUS: queue full, a byte waits, room to transmit.
irq, dmaThe interrupt request and the DMA request of UART0.
busThree clock edges of the read of RXDATA: the address, the setup phase, the access phase.
read byteThe byte that the read of RXDATA returned, in hexadecimal. 4b is the letter K.
terminal receivedThe letter that a second receiver, on the TX wire, rebuilt from the bits.
tx bitsThe TX wire in the middle of each of the ten bit times. The first bit is on the left.
frameThe number of clocks the transmitter needed for one byte.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: idle status=001 irq=0 dma=0 one byte status=011 irq=1 dma=0 two bytes status=111 irq=1 dma=1 bus req=1 sel=0 enable=0 ready=1 bus req=0 sel=1 enable=0 ready=0 bus req=0 sel=1 enable=1 ready=1 read byte=4b after read status=011 irq=1 dma=0 sending status=010 irq=1 dma=0 terminal received=K sent status=011 irq=1 dma=0 tx bits=0110100101 frame=160 clocks
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: receiver.sv
`timescale 1ns/1ps
module uart_rx(input wire clk, rst_n, rx, take,
  output reg [7:0] data=0, output reg valid=0, frame_err=0, parity_err=0, overrun=0, break_seen=0, frame_done=0);
  int bits=8, parity=0; real stop_bits=1.0;
  bit trace=0;
  bit parity_includes_start=0; // XOR of the zero-valued START is an equivalent control.
  bit sample_at_edge=0, qualify_1_tick=0, no_vote=0, no_resync=0, rearm_on_low=0, stop_as_data=0, no_overrun_flag=0, parity_includes_stop=0;
  int state=0, low_run=0, left_ticks=0, index=0, votes=0, frames=0, ticks=0, next_data_tick=0;
  bit armed=1, sampled=0, p=0, pe=0, pending_zero_fe=0; reg [7:0] shift=0;
  always @(posedge clk) begin
    frame_done=0;
    if(!rst_n) begin state=0;low_run=0;left_ticks=0;index=0;votes=0;valid=0;data=0;frame_err=0;parity_err=0;overrun=0;break_seen=0;armed=1;frames=0;ticks=0;next_data_tick=0;pending_zero_fe=0; end
    else begin
      ticks++;
      if(take)valid=0;
      low_run=rx?0:low_run+1;
      if(rx)break_seen=0;
      if(low_run>=176&&!rearm_on_low)begin break_seen=1;state=4;pending_zero_fe=0;end
      if(state==4)begin if(rx)begin
        if(pending_zero_fe)begin
          if(valid&&!no_overrun_flag)overrun=1;
          data=0;valid=1;frame_err=1;parity_err=pe;frames++;frame_done=1;pending_zero_fe=0;
        end
        state=0;armed=1;
      end end
      else if(state==0)begin
        if(rx)begin armed=1;end
        else if(armed&&low_run>=(qualify_1_tick?1:8))begin
          state=1;left_ticks=sample_at_edge?8:16;index=0;shift=0;p=(parity==2)^parity_includes_stop;votes=0;pe=0;
          // Fault: later frames keep the first frame's free-running schedule.
          // At nominal back-to-back pacing it can work; a new START must normally
          // reset this timing so baud error cannot accumulate across frames.
          if(no_resync&&frames>0)begin
            while(next_data_tick<=ticks)next_data_tick+=16*(1+bits+(parity!=0))+$rtoi(16*stop_bits);
            left_ticks=next_data_tick-ticks;
          end else next_data_tick=ticks+left_ticks;
          next_data_tick+=16*(1+bits+(parity!=0))+$rtoi(16*stop_bits);
        end
      end else begin
        if(left_ticks<=3)votes=votes+(rx?1:0);
        left_ticks=left_ticks-1;
        if(left_ticks==0)begin
          sampled=no_vote?rx:(votes>=2);votes=0;left_ticks=16;
          if(trace)$display("UART SAMPLE t=%0t state=%0d bit=%0d value=%0d",$time,state,index,sampled);
          if(state==1)begin shift[index]=sampled;p=p^sampled;index=index+1;if(index==bits)state=parity==0?3:2;end
          else if(state==2)begin pe=(sampled!=p);state=3;end
          else begin
            if(shift==0&&!sampled&&!rearm_on_low)pending_zero_fe=1;
            else begin
              if(valid&&!no_overrun_flag)overrun=1;
              data=stop_as_data?{sampled,shift[7:1]}:shift;
              frame_err=!sampled;parity_err=pe;valid=1;frames=frames+1;frame_done=1;
            end
            state=(sampled||rearm_on_low)?0:4;armed=1;
          end
        end
      end
    end
  end
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 reads the first byte before the second one arrives. What is the last row the lab prints?
`timescale 1ns/1ns
module tb;
  `include "bus.svh"
  localparam TXDATA=32'h10000000, STATUS=32'h10000004, RXDATA=32'h1000000c;   // registers of UART0
  logic rx=1;                       // the wire from the terminal into the chip; it rests at 1
  wire tx;                          // the wire from the chip to the terminal
  wire irq, dma_req;                // the two service requests of UART0
  wire [7:0] rx_data, echo;
  wire rx_valid, echo_valid;
  logic [7:0] letter;
  // Gathers the bits on rx into one byte. UART0 puts each finished byte into its queue.
  uart_rx receiver(.clk(hclk),.rst_n(hresetn),.rx,.take(rx_valid),.data(rx_data),.valid(rx_valid));
  // Stands in for the terminal: it rebuilds a byte from the bits on tx.
  uart_rx terminal(.clk(hclk),.rst_n(hresetn),.rx(tx),.take(1'b0),.data(echo),.valid(echo_valid));
  reg sample_valid;
  always @(negedge hclk) sample_valid <= rx_valid;
  serial_slice device(.clk(hclk),.reset_n(hresetn),.sel(psel),.enable(penable),
    .wr(pwrite),.addr(paddr),.wdata(pwdata),.rdata(prdata),.rx_done(sample_valid),
    .rx_data,.tx,.irq,.dma_req,.cs_n(),.sclk(),.mosi(),.miso(1'b0));
  int frame_clocks=0;               // clocks for which the transmitter is busy with one frame
  string tx_bits="";                // the level of tx in the middle of each bit, first bit on the left
  always @(posedge hclk) if (device.bits_left != 0) begin
    frame_clocks++;
    if (device.tick == 8) tx_bits={tx_bits, tx ? "1" : "0"};
  end
  // The terminal sends one frame: a start bit (0), eight data bits, a stop bit (1). 16 clocks for each bit.
  task automatic send(input logic [7:0] value);
    logic [9:0] frame;
    frame={1'b1,value,1'b0};
    for(int i=0;i<10;i++) begin
      rx=frame[i];
      repeat(16) @(negedge hclk);
    end
    repeat(8) @(negedge hclk);
  endtask
  // Software reads STATUS. Bits: 2 = queue full, 1 = a byte waits, 0 = room to transmit.
  task automatic status(input string label);
    access_word(0, STATUS, 0, result);
    $display("%s status=%03b irq=%b dma=%b", label, result[2:0], irq, dma_req);
  endtask
  task automatic take(input string label);
    access_word(0, RXDATA, 0, result);
    $display("%s byte=%02h", label, result[7:0]);
  endtask
  initial begin
    repeat (2) @(negedge hclk);
    hresetn=1;
    send("K");
    status("one byte");
    take("first read");
    send("?");
    status("second byte");
    $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: receiver.sv
`timescale 1ns/1ps
module uart_rx(input wire clk, rst_n, rx, take,
  output reg [7:0] data=0, output reg valid=0, frame_err=0, parity_err=0, overrun=0, break_seen=0, frame_done=0);
  int bits=8, parity=0; real stop_bits=1.0;
  bit trace=0;
  bit parity_includes_start=0; // XOR of the zero-valued START is an equivalent control.
  bit sample_at_edge=0, qualify_1_tick=0, no_vote=0, no_resync=0, rearm_on_low=0, stop_as_data=0, no_overrun_flag=0, parity_includes_stop=0;
  int state=0, low_run=0, left_ticks=0, index=0, votes=0, frames=0, ticks=0, next_data_tick=0;
  bit armed=1, sampled=0, p=0, pe=0, pending_zero_fe=0; reg [7:0] shift=0;
  always @(posedge clk) begin
    frame_done=0;
    if(!rst_n) begin state=0;low_run=0;left_ticks=0;index=0;votes=0;valid=0;data=0;frame_err=0;parity_err=0;overrun=0;break_seen=0;armed=1;frames=0;ticks=0;next_data_tick=0;pending_zero_fe=0; end
    else begin
      ticks++;
      if(take)valid=0;
      low_run=rx?0:low_run+1;
      if(rx)break_seen=0;
      if(low_run>=176&&!rearm_on_low)begin break_seen=1;state=4;pending_zero_fe=0;end
      if(state==4)begin if(rx)begin
        if(pending_zero_fe)begin
          if(valid&&!no_overrun_flag)overrun=1;
          data=0;valid=1;frame_err=1;parity_err=pe;frames++;frame_done=1;pending_zero_fe=0;
        end
        state=0;armed=1;
      end end
      else if(state==0)begin
        if(rx)begin armed=1;end
        else if(armed&&low_run>=(qualify_1_tick?1:8))begin
          state=1;left_ticks=sample_at_edge?8:16;index=0;shift=0;p=(parity==2)^parity_includes_stop;votes=0;pe=0;
          // Fault: later frames keep the first frame's free-running schedule.
          // At nominal back-to-back pacing it can work; a new START must normally
          // reset this timing so baud error cannot accumulate across frames.
          if(no_resync&&frames>0)begin
            while(next_data_tick<=ticks)next_data_tick+=16*(1+bits+(parity!=0))+$rtoi(16*stop_bits);
            left_ticks=next_data_tick-ticks;
          end else next_data_tick=ticks+left_ticks;
          next_data_tick+=16*(1+bits+(parity!=0))+$rtoi(16*stop_bits);
        end
      end else begin
        if(left_ticks<=3)votes=votes+(rx?1:0);
        left_ticks=left_ticks-1;
        if(left_ticks==0)begin
          sampled=no_vote?rx:(votes>=2);votes=0;left_ticks=16;
          if(trace)$display("UART SAMPLE t=%0t state=%0d bit=%0d value=%0d",$time,state,index,sampled);
          if(state==1)begin shift[index]=sampled;p=p^sampled;index=index+1;if(index==bits)state=parity==0?3:2;end
          else if(state==2)begin pe=(sampled!=p);state=3;end
          else begin
            if(shift==0&&!sampled&&!rearm_on_low)pending_zero_fe=1;
            else begin
              if(valid&&!no_overrun_flag)overrun=1;
              data=stop_as_data?{sampled,shift[7:1]}:shift;
              frame_err=!sampled;parity_err=pe;valid=1;frames=frames+1;frame_done=1;
            end
            state=(sampled||rearm_on_low)?0:4;armed=1;
          end
        end
      end
    end
  end
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
ConceptHow does a receiver find the bits when no clock wire comes with them?
ConceptOne bit time is 16 clocks. How many clocks does a frame of eight data bits last?
ConceptTwo bytes wait in the queue. Software reads RXDATA once. What does it get?
ConceptWhat is a watermark?
ConceptThe queue of this UART is full, and one more byte arrives. What happens?

Common Mistakes

Wrong Take the interrupt as the byte.

The request says that a byte waits. It carries no data.

Fix Read RXDATA. The byte leaves the queue on that read.

Wrong Change the clock of the chip and keep the bit count.

The bit time is a count of clocks, so it changes with the clock.

Fix Work the count out again from the new clock and the baud rate.

Wrong Size the queue by the average flow of bytes.

Bytes are lost in the longest gap between two reads, not in the average one.

Fix Compare the room left at the watermark with the longest delay of the service.

Remember

  • A UART sends a byte as a frame on one wire, with no clock wire. The frame is a start bit, eight data bits and a stop bit.
  • Each end counts the bit time on its own clock. Here it is 16 clocks, so a frame lasts 160.
  • Received bytes wait in a queue. A read of RXDATA returns the oldest and removes it.
  • A request is 1 while the queue holds its watermark or more. A byte that meets a full queue is lost.

Practice

Report a problem with this page