Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A UART Transmitter and Receiver

Build a UART in Verilog with a baud rate generator, an 8N1 transmitter FSM and a receiver that samples mid-bit, and study the frame format with C stand-ins.

The UART (universal asynchronous receiver-transmitter) is the serial port that every microcontroller, FPGA board and debug console uses. It is a rewarding project: small enough to finish in an afternoon, yet it exercises everything you have learned: clock division, FSMs, shift registers, a testbench with timing, and the receiver's problem of sampling a signal with no shared clock.

You will learn the 8N1 frame, compute the baud divider, write the transmitter and receiver, and check the bit-level behaviour with C stand-ins. Verilog is read-only here (no simulator runs on this site); the C programs are labelled stand-ins that generate and decode the same frames. Review FSM coding styles first if needed.

The 8N1 frame

UART sends one byte at a time on a single wire, with no clock. Both sides agree on a baud rate (bits per second) in advance. The line idles high (1). A frame is:

  1. Start bit: the line goes low (0) for one bit time.
  2. 8 data bits, least significant bit first.
  3. Stop bit: the line returns high (1) for one bit time (the "1" in 8N1; "N" means no parity).

So the byte 0x41 ('A', binary 01000001) is sent as: start 0, then bits 1,0,0,0,0,0,1,0 (LSB first), then stop 1. Ten bit times per byte, so at 115,200 baud a byte takes 86.8 microseconds and the payload rate is 11,520 bytes per second.

stateDiagram-v2
  [*] --> IDLE
  IDLE --> START: send
  START --> DATA: bit time done
  DATA --> DATA: bit time done, bits left
  DATA --> STOP: bit time done, last bit
  STOP --> IDLE: bit time done

Transmitter states: each transition happens once per bit time.

Baud rate generator

The design runs on a fast system clock (say 50 MHz). To get one-bit-long periods, count clock cycles:

TEXT
CLKS_PER_BIT = clock_frequency / baud_rate

With 50 MHz and 115,200 baud the ideal value is 434.03, so we use 434, an error of 0.007%, which is far below the roughly 2 to 3% a UART tolerates over a 10-bit frame (each side's error accumulates up to 9.5 bits before the stop bit is sampled). The first stand-in computes divisors and the resulting error for several clocks and rates:

C Stand-in: baud divider and rate error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice how the divisor shrinks as the baud rate rises: at 921,600 baud on 12 MHz it is only 13, and rounding it costs 0.16%; on 50 MHz the same baud rate needs 54 and is off by 0.47%. All of these are far inside the 2 to 3% a receiver tolerates, but a smaller divisor leaves less room for oversampling. Use a divisor of at least 16 if you want 16x oversampling in the receiver.

The transmitter in Verilog

VERILOG
module uart_tx #(
  parameter CLKS_PER_BIT = 434
) (
  input            clk, rst_n,
  input            send,          // pulse: start sending 'data'
  input      [7:0] data,
  output reg       tx,
  output           busy
);
  localparam IDLE = 2'd0, START = 2'd1, DATA = 2'd2, STOP = 2'd3;

  reg [1:0]  state;
  reg [15:0] clk_count;
  reg [2:0]  bit_index;
  reg [7:0]  shifter;

  assign busy = (state != IDLE);

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      state <= IDLE; tx <= 1'b1; clk_count <= 0; bit_index <= 0; shifter <= 0;
    end else begin
      case (state)
        IDLE: begin
          tx <= 1'b1;
          if (send) begin
            shifter <= data; clk_count <= 0; state <= START;
          end
        end
        START: begin
          tx <= 1'b0;                                   // start bit
          if (clk_count == CLKS_PER_BIT - 1) begin
            clk_count <= 0; bit_index <= 0; state <= DATA;
          end else clk_count <= clk_count + 1;
        end
        DATA: begin
          tx <= shifter[bit_index];                     // LSB first
          if (clk_count == CLKS_PER_BIT - 1) begin
            clk_count <= 0;
            if (bit_index == 3'd7) state <= STOP;
            else bit_index <= bit_index + 1;
          end else clk_count <= clk_count + 1;
        end
        STOP: begin
          tx <= 1'b1;                                   // stop bit
          if (clk_count == CLKS_PER_BIT - 1) begin
            clk_count <= 0; state <= IDLE;
          end else clk_count <= clk_count + 1;
        end
      endcase
    end
  end
endmodule

The design is a Moore machine with a counter timing each state, as in the traffic light example. The tx register means the output is glitch-free; busy tells the user when it is safe to send again (a send while busy is ignored).

The frame as a bit stream

The second stand-in builds the transmitted waveform from the same rules: it expands each byte of a string into the 10-bit frame and then prints the line level over time, one character per bit. Then it decodes the stream, as a receiver would: it finds the falling edge of a start bit, jumps to the middle of the start bit, and samples each following bit at one-bit intervals.

C Stand-in: framing bytes and decoding them from the line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You see the pattern of high and low levels for each byte, and the decoder recovers Hi! from nothing but the line. Sampling in the middle of each bit is the key idea: edges are where the signal is changing and unreliable, the centre is the safest point, and it tolerates the clock mismatch between the two sides.

The receiver in Verilog

A real receiver cannot see the sender's clock, so it detects the start bit's falling edge, waits half a bit, confirms the line is still low, and then samples every bit time:

VERILOG
module uart_rx #(
  parameter CLKS_PER_BIT = 434
) (
  input            clk, rst_n, rx,
  output reg [7:0] data,
  output reg       valid          // one-cycle pulse when a byte has arrived
);
  localparam IDLE = 2'd0, START = 2'd1, DATA = 2'd2, STOP = 2'd3;

  reg rx_sync1, rx_sync2;                                 // 2-flop synchronizer
  always @(posedge clk) begin rx_sync1 <= rx; rx_sync2 <= rx_sync1; end

  reg [1:0]  state;
  reg [15:0] clk_count;
  reg [2:0]  bit_index;

  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      state <= IDLE; clk_count <= 0; bit_index <= 0; data <= 0; valid <= 0;
    end else begin
      valid <= 1'b0;
      case (state)
        IDLE: if (!rx_sync2) begin clk_count <= 0; state <= START; end
        START: begin
          if (clk_count == (CLKS_PER_BIT - 1) / 2) begin   // middle of the start bit
            if (!rx_sync2) begin clk_count <= 0; bit_index <= 0; state <= DATA; end
            else state <= IDLE;                             // glitch
          end else clk_count <= clk_count + 1;
        end
        DATA: begin
          if (clk_count == CLKS_PER_BIT - 1) begin          // next bit centre
            clk_count <= 0;
            data[bit_index] <= rx_sync2;
            if (bit_index == 3'd7) state <= STOP;
            else bit_index <= bit_index + 1;
          end else clk_count <= clk_count + 1;
        end
        STOP: begin
          if (clk_count == CLKS_PER_BIT - 1) begin
            valid <= rx_sync2;                              // stop bit must be 1
            state <= IDLE;
          end else clk_count <= clk_count + 1;
        end
      endcase
    end
  end
endmodule

Two details are essential. The rx pin is asynchronous, so it passes through a two-flop synchronizer (clock domain crossing). And the receiver checks the stop bit: if it is 0 the frame is rejected, a framing error.

Testing it

A loopback testbench wires tx into rx, sends several bytes (including 0x00, 0xFF, 0x55 and 0xAA, the alternating patterns that stress edge handling) and checks that valid pulses with the same data. A smaller CLKS_PER_BIT such as 16 keeps simulation fast:

VERILOG
`timescale 1ns/1ps
module uart_tb;
  reg clk = 0, rst_n = 0, send = 0;
  reg [7:0] tx_data;
  wire tx, busy, valid;
  wire [7:0] rx_data;
  integer i, errors = 0;
  reg [7:0] tests [0:5];

  always #5 clk = ~clk;

  uart_tx #(.CLKS_PER_BIT(16)) txu (.clk(clk), .rst_n(rst_n), .send(send),
                                    .data(tx_data), .tx(tx), .busy(busy));
  uart_rx #(.CLKS_PER_BIT(16)) rxu (.clk(clk), .rst_n(rst_n), .rx(tx),
                                    .data(rx_data), .valid(valid));

  initial begin
    tests[0] = 8'h00; tests[1] = 8'hFF; tests[2] = 8'h55;
    tests[3] = 8'hAA; tests[4] = 8'h41; tests[5] = 8'h7E;
    #50 rst_n = 1;
    for (i = 0; i < 6; i = i + 1) begin
      @(posedge clk); tx_data = tests[i]; send = 1;
      @(posedge clk); send = 0;
      @(posedge valid);
      if (rx_data !== tests[i]) begin
        errors = errors + 1;
        $display("FAIL: sent %h received %h", tests[i], rx_data);
      end
    end
    if (errors == 0) $display("PASS"); else $display("FAIL: %0d", errors);
    $finish;
  end
endmodule

Add a timeout (see stimulus and system tasks) so a hung receiver does not run forever.

Extensions

  • Add parity (even or odd) and a parity-error output.
  • Add 16x oversampling and majority voting of three samples for noise immunity.
  • Add a small TX FIFO so a CPU can queue bytes while the line is busy (FIFO project).
  • Make the baud divisor a register that software can set.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In an 8N1 frame, in which order are the data bits sent?

    UARTs send the least significant bit first, after the low start bit and before the high stop bit.
  2. 2. How many bit times does an 8N1 byte take on the line?

    One start bit, 8 data bits and one stop bit make 10 bit times.
  3. 3. Why does the receiver sample in the middle of each bit?

    Edges are where the line changes and may be skewed; sampling at the centre gives the most margin.
  4. 4. Why does the receiver pass the rx pin through two flip-flops first?

    The incoming line has no relationship to the local clock, so a two-flop synchronizer is required.

Summary

  • A UART frame is a low start bit, 8 data bits LSB first, and a high stop bit; the line idles high.
  • The baud divider is clock / baud; check the rounding error and use oversampling when possible.
  • The transmitter is a counter-timed FSM with a shift register; the receiver synchronizes the input, detects the start edge and samples at bit centres.
  • Test with a loopback and edge-stressing patterns such as 0x00, 0xFF, 0x55, 0xAA.

Next: Project: A Synchronous FIFO