// UART receiver, 8N1, with a two-flop input synchroniser and mid-bit sampling. // rx_valid pulses for one clock when a byte with a good stop bit arrives. // rx_frame_err pulses instead when the stop bit is sampled low. `timescale 1ns / 1ps module uart_rx #( parameter int CLK_FREQ = 100_000_000, parameter int BAUD = 115_200 ) ( input logic clk, input logic rst, // synchronous, active high input logic rxd, // asynchronous serial input output logic [7:0] rx_data, output logic rx_valid, output logic rx_frame_err ); localparam int CLKS_PER_BIT = (CLK_FREQ + BAUD / 2) / BAUD; localparam int HALF_BIT = CLKS_PER_BIT / 2; localparam int CW = $clog2(CLKS_PER_BIT + 1); // Two-flop synchroniser. rxd comes from another clock domain (the PC), // so the first flop may go metastable; only rx_sync is used below. (* ASYNC_REG = "TRUE" *) logic rx_meta; (* ASYNC_REG = "TRUE" *) logic rx_sync; always_ff @(posedge clk) begin if (rst) begin rx_meta <= 1'b1; // line idles high rx_sync <= 1'b1; end else begin rx_meta <= rxd; rx_sync <= rx_meta; end end typedef enum logic [1:0] {S_IDLE, S_START, S_DATA, S_STOP} state_t; state_t state; logic [CW-1:0] baud_cnt; logic [2:0] bit_idx; logic [7:0] shreg; always_ff @(posedge clk) begin if (rst) begin state <= S_IDLE; baud_cnt <= '0; bit_idx <= 3'd0; shreg <= 8'h00; rx_data <= 8'h00; rx_valid <= 1'b0; rx_frame_err <= 1'b0; end else begin rx_valid <= 1'b0; // default: one-cycle pulses rx_frame_err <= 1'b0; case (state) // Wait for the falling edge of the start bit. S_IDLE: begin baud_cnt <= '0; if (!rx_sync) state <= S_START; end // Wait half a bit, then check that the line is still low. S_START: begin if (baud_cnt == CW'(HALF_BIT - 1)) begin baud_cnt <= '0; bit_idx <= 3'd0; if (!rx_sync) state <= S_DATA; // real start bit else state <= S_IDLE; // glitch: ignore end else begin baud_cnt <= baud_cnt + 1'b1; end end // Sample each data bit one full bit time later, mid-bit. S_DATA: begin if (baud_cnt == CW'(CLKS_PER_BIT - 1)) begin baud_cnt <= '0; shreg <= {rx_sync, shreg[7:1]}; // LSB first if (bit_idx == 3'd7) state <= S_STOP; else bit_idx <= bit_idx + 3'd1; end else begin baud_cnt <= baud_cnt + 1'b1; end end // Sample the stop bit mid-bit. Return to idle straight away, // so the next start bit can be caught early. S_STOP: begin if (baud_cnt == CW'(CLKS_PER_BIT - 1)) begin baud_cnt <= '0; state <= S_IDLE; if (rx_sync) begin rx_data <= shreg; rx_valid <= 1'b1; end else begin rx_frame_err <= 1'b1; end end else begin baud_cnt <= baud_cnt + 1'b1; end end default: state <= S_IDLE; endcase end end endmodule