Home / Learn Chip Programming / UART in Verilog: Transmitter and Receiver

UART in Verilog: Transmitter and Receiver

Build a real serial port in hardware, 115200 baud 8N1.

In shortBuild a real serial port in hardware, 115200 baud 8N1.

Theory in plain words

TX frameidle highstart bit 0D0 ... D7 (LSB first)stop bit 1
TX frame

What it is

A UART TX shifts out a start bit, 8 data bits LSB first and a stop bit at the baud rate. The RX samples the line at the middle of each bit after detecting the start edge, using a 16x oversampling or tick counter.

Why we use it

UART is the first interface you add to any FPGA design: debug prints and PC control.

How it works

Baud tick = clk / baud. TX state machine: IDLE, START, DATA (count 8), STOP. RX: wait for falling edge, wait half bit, sample each bit mid-bit, check stop.

Where it is used

  • FPGA debug console
  • PC to FPGA commands
  • Part of the FPGA UART + VGA project

UART frame and baud divider

Frame bits and clock dividerTry it Yourself

Integer clock division gives tiny baud errors with a fast FPGA clock. Receivers sample in the middle of each bit.

UART transmitter
module uart_tx #(parameter CLKS_PER_BIT = 234) (input clk, input start, input [7:0] data, output reg tx = 1, output reg busy = 0);
    localparam IDLE = 0, START = 1, DATA = 2, STOP = 3;
    reg [1:0] st = IDLE; reg [15:0] cnt = 0; reg [2:0] bit_i = 0; reg [7:0] sh = 0;
    always @(posedge clk) case (st)
        IDLE:  begin tx <= 1; if (start) begin sh <= data; busy <= 1; cnt <= 0; st <= START; end end
        START: begin tx <= 0; if (cnt == CLKS_PER_BIT-1) begin cnt <= 0; bit_i <= 0; st <= DATA; end else cnt <= cnt + 1; end
        DATA:  begin tx <= sh[bit_i]; if (cnt == CLKS_PER_BIT-1) begin cnt <= 0; if (bit_i == 7) st <= STOP; else bit_i <= bit_i + 1; end else cnt <= cnt + 1; end
        STOP:  begin tx <= 1; if (cnt == CLKS_PER_BIT-1) begin busy <= 0; st <= IDLE; end else cnt <= cnt + 1; end
    endcase
endmodule
Tip:Test with a USB-UART adapter (CP2102/CH340) and a terminal at 115200. Cross TX to RX and share ground. Many boards (Tang Nano) already have a USB serial on the board.

Quick quiz

1. UART data order?

2. RX samples...