Skip to content
systemcoding.dev
Hardware

Implement a UART Transmitter and Receiver in Verilog

Write an 8N1 UART transmitter and receiver in Verilog with mid-bit sampling and a loopback testbench that sends 0x55 and 0xA3 and checks the bytes.

7 min read
Summarize in AI
Flat illustration of logic gates wired into a small circuit, with the SparkFun, Haskell and KiCad logos.

A UART is the oldest serial link in electronics and still the one you reach for first: two wires, no clock, and a format simple enough to build in an afternoon. Building it yourself in Verilog teaches the three ideas every serial receiver needs, which are a counter that converts a fast system clock into bit times, a state machine that follows the frame, and a decision about where inside a bit to sample. This post implements the common 8N1 frame (one start bit, eight data bits least significant first, no parity, one stop bit), verifies it in simulation with a loopback testbench using Icarus Verilog 12.0, and then shows the real baud rate arithmetic for a 50 MHz clock at 115200 baud. The reader is assumed to know basic Verilog state machines.

The frame on the wire

The line idles high. A byte starts with the line pulled low for one bit time, the start bit. The eight data bits follow, least significant first, each held for one bit time. The frame ends with the line high for at least one bit time, the stop bit. For 0x55, which is 01010101, the transmitted levels are low (start), then 1, 0, 1, 0, 1, 0, 1, 0 (the bits from least to most significant), then high (stop). A UART frame carries no clock, so both sides must agree on the bit time beforehand and the receiver must resynchronise on every start bit.

Bit time is the system clock frequency divided by the baud rate. For simulation this post uses four system clocks per bit so that waveforms stay short; for hardware, 50 MHz divided by 115200 is 434.03, so a counter that counts 434 clocks per bit runs 0.0064 per cent slow, far inside the tolerance of a ten-bit frame.

The transmitter

The transmitter is a four-state machine. It idles, drives the start bit, shifts the eight data bits and drives the stop bit, counting CLKS_PER_BIT system clocks in each state.

uart_tx.vverilog
module uart_tx #(
    parameter CLKS_PER_BIT = 434
) (
    input  wire       clk,
    input  wire       rst,
    input  wire [7:0] data,
    input  wire       start,
    output reg        busy,
    output reg        tx
);
    localparam IDLE = 2'd0, START = 2'd1, DATA = 2'd2, STOP = 2'd3;

    reg [1:0]  state;
    reg [15:0] clk_cnt;
    reg [2:0]  bit_idx;
    reg [7:0]  shreg;

    always @(posedge clk) begin
        if (rst) begin
            state   <= IDLE;
            tx      <= 1'b1;
            busy    <= 1'b0;
            clk_cnt <= 16'd0;
            bit_idx <= 3'd0;
        end else begin
            case (state)
                IDLE: begin
                    tx   <= 1'b1;
                    busy <= 1'b0;
                    if (start) begin
                        shreg   <= data;
                        busy    <= 1'b1;
                        clk_cnt <= 16'd0;
                        tx      <= 1'b0;
                        state   <= START;
                    end
                end
                START: begin
                    if (clk_cnt == CLKS_PER_BIT - 1) begin
                        clk_cnt <= 16'd0;
                        bit_idx <= 3'd0;
                        tx      <= shreg[0];
                        state   <= DATA;
                    end else
                        clk_cnt <= clk_cnt + 16'd1;
                end
                DATA: begin
                    if (clk_cnt == CLKS_PER_BIT - 1) begin
                        clk_cnt <= 16'd0;
                        if (bit_idx == 3'd7) begin
                            tx    <= 1'b1;
                            state <= STOP;
                        end else begin
                            bit_idx <= bit_idx + 3'd1;
                            tx      <= shreg[bit_idx + 3'd1];
                        end
                    end else
                        clk_cnt <= clk_cnt + 16'd1;
                end
                STOP: begin
                    if (clk_cnt == CLKS_PER_BIT - 1) begin
                        clk_cnt <= 16'd0;
                        busy    <= 1'b0;
                        state   <= IDLE;
                    end else
                        clk_cnt <= clk_cnt + 16'd1;
                end
            endcase
        end
    end
endmodule

The key move is that tx is a register assigned when the state changes, so the output is glitch-free and changes exactly on a clock edge. shreg holds a copy of the byte so the caller may change data after pulsing start. busy goes high when the frame begins and low again at the end of the stop bit, which is what a caller waits on before sending the next byte.

The receiver

The receiver has the harder job because it must find the frame without a clock. It uses two decisions. First, it synchronises the incoming rx with two flip-flops, since the line comes from another clock domain, or from outside the chip. Second, it samples each bit in the middle of its bit time, where the signal is farthest from both edges.

uart_rx.vverilog
module uart_rx #(
    parameter CLKS_PER_BIT = 434
) (
    input  wire       clk,
    input  wire       rst,
    input  wire       rx,
    output reg  [7:0] data,
    output reg        valid
);
    localparam IDLE = 2'd0, START = 2'd1, DATA = 2'd2, STOP = 2'd3;

    reg [1:0]  rx_sync;
    reg [1:0]  state;
    reg [15:0] clk_cnt;
    reg [2:0]  bit_idx;

    always @(posedge clk)
        rx_sync <= {rx_sync[0], rx};

    wire rx_s = rx_sync[1];

    always @(posedge clk) begin
        valid <= 1'b0;
        if (rst) begin
            state   <= IDLE;
            clk_cnt <= 16'd0;
            bit_idx <= 3'd0;
        end else begin
            case (state)
                IDLE: begin
                    if (!rx_s) begin
                        clk_cnt <= 16'd0;
                        state   <= START;
                    end
                end
                START: begin
                    if (clk_cnt == (CLKS_PER_BIT - 1) / 2) begin
                        if (!rx_s) begin
                            clk_cnt <= 16'd0;
                            bit_idx <= 3'd0;
                            state   <= DATA;
                        end else
                            state <= IDLE;
                    end else
                        clk_cnt <= clk_cnt + 16'd1;
                end
                DATA: begin
                    if (clk_cnt == CLKS_PER_BIT - 1) begin
                        clk_cnt       <= 16'd0;
                        data[bit_idx] <= rx_s;
                        if (bit_idx == 3'd7)
                            state <= STOP;
                        else
                            bit_idx <= bit_idx + 3'd1;
                    end else
                        clk_cnt <= clk_cnt + 16'd1;
                end
                STOP: begin
                    if (clk_cnt == CLKS_PER_BIT - 1) begin
                        valid   <= rx_s;
                        state   <= IDLE;
                        clk_cnt <= 16'd0;
                    end else
                        clk_cnt <= clk_cnt + 16'd1;
                end
            endcase
        end
    end
endmodule

The START state waits half a bit time and checks that the line is still low. A short glitch on an idle line therefore does not start a frame, and the counter is restarted at the middle of the start bit. From there, every CLKS_PER_BIT clocks is the middle of the next bit, which is where DATA samples. In the STOP state the receiver sets valid only if the stop bit really is high, so a framing error is reported as a missing valid instead of a wrong byte.

A loopback testbench

Connect tx to rx and send two bytes with four clocks per bit.

uart_tb.vverilog
`timescale 1ns/1ps

module uart_tb;
    reg        clk   = 1'b0;
    reg        rst   = 1'b1;
    reg  [7:0] data  = 8'h00;
    reg        start = 1'b0;
    wire       busy;
    wire       line;
    wire [7:0] rx_data;
    wire       rx_valid;

    uart_tx #(.CLKS_PER_BIT(4)) tx0 (
        .clk(clk), .rst(rst), .data(data), .start(start), .busy(busy), .tx(line)
    );
    uart_rx #(.CLKS_PER_BIT(4)) rx0 (
        .clk(clk), .rst(rst), .rx(line), .data(rx_data), .valid(rx_valid)
    );

    always #5 clk = ~clk;

    always @(posedge clk)
        if (rx_valid)
            $display("received 0x%02h", rx_data);

    task send(input [7:0] b);
        begin
            @(posedge clk);
            data  <= b;
            start <= 1'b1;
            @(posedge clk);
            start <= 1'b0;
            wait (busy);
            wait (!busy);
            repeat (4) @(posedge clk);
        end
    endtask

    initial begin
        #30 rst = 1'b0;
        #40;
        send(8'h55);
        send(8'hA3);
        $finish;
    end
endmodule
Shell
iverilog -g2012 -o uart_sim uart_tx.v uart_rx.v uart_tb.v
vvp uart_sim
Text
received 0x55
received 0xa3

A valid pulse and a matching byte for each frame show that start-bit detection, mid-bit sampling and the stop-bit check all work. Open a waveform of line for the first frame and you see the pattern low, 1, 0, 1, 0, 1, 0, 1, 0, high, each level lasting 40 ns.

The real baud rate

For hardware replace the parameter with the arithmetic. At 50 MHz and 115200 baud, bit time is 434.03 clocks, so CLKS_PER_BIT = 434 makes the bit 0.0064 per cent short. The receiver samples at the middle of bit 0 and at 434-clock steps after it, so by the stop bit the sample point has drifted by about 3.9 clocks of an exact 4340-clock frame, a small fraction of the half-bit margin of 217 clocks. The permitted error is a few per cent in total between both ends, which is why standard rates work across devices with different crystals. When the divisor is not close to an integer, as at 3 Mbaud on a 50 MHz clock, the rounding error grows to several per cent and a fractional divider is the cure; a separate post covers that.

Choosing the divisor for your clock

The divisor is the system clock divided by the baud rate, rounded to an integer, and the rounding error becomes a baud error. The table gives the actual baud rate and its error for common clocks and rates:

System clockBaud rateExact divisorUsedActual baudError
50 MHz115200434.03434115207+0.006%
48 MHz115200416.67417115108-0.080%
12 MHz115200104.17104115385+0.160%
50 MHz92160054.2554925926+0.469%
50 MHz300000016.67172941176-1.961%

Both ends together must stay within a few per cent, so the first three rows are comfortable and the last is risky when the other device has its own error. Mid-bit sampling needs at least a handful of clocks per bit to place the sample point well; at 17 clocks per bit it is workable, and below about 8 the sample position is too coarse to trust.

Adding parity and reporting errors

Parity is one more bit between the data and the stop bit. Even parity makes the total number of ones in data plus parity even, so the transmitter sends the XOR of the data bits:

verilog
wire parity_bit = ^shreg;

The transmitter gains a PARITY state that drives parity_bit for one bit time before STOP. The receiver gains the matching state, compares ^data with the sampled bit and raises a parity error flag when they differ. The two other errors a receiver should expose are a framing error, when the stop bit is low, and an overrun, when a new byte arrives before the previous one was read. In the receiver above a framing error simply produces no valid pulse, which hides the fault; a production design adds an error output so software can count them. Counting is the useful part: a rising framing-error count with correct data usually means the baud rates are slightly off.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.