| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- `timescale 1ns/1ps
- module uart_rx_byte #(
- parameter integer CLKS_PER_BIT = 217
- ) (
- input wire clk,
- input wire rst_n,
- input wire rx_i,
- output reg byte_valid,
- output reg [7:0] byte_data,
- output reg framing_error
- );
- localparam integer HALF_BIT = (CLKS_PER_BIT < 2) ? 1 : (CLKS_PER_BIT / 2);
- localparam integer COUNTER_BITS = (CLKS_PER_BIT <= 2) ? 1 : $clog2(CLKS_PER_BIT);
- /* verilator lint_off WIDTH */
- localparam [COUNTER_BITS-1:0] BIT_LAST = CLKS_PER_BIT - 1;
- localparam [COUNTER_BITS-1:0] HALF_LAST = HALF_BIT - 1;
- /* verilator lint_on WIDTH */
- localparam [1:0] ST_IDLE = 2'd0;
- localparam [1:0] ST_START = 2'd1;
- localparam [1:0] ST_DATA = 2'd2;
- localparam [1:0] ST_STOP = 2'd3;
- reg [1:0] rx_sync_pipe;
- reg [1:0] state;
- reg [COUNTER_BITS-1:0] bit_counter;
- reg [2:0] bit_index;
- reg [7:0] data_reg;
- // Keep the asynchronous input synchronizer on an ordinary, explicitly
- // clocked two-flop path. TD maps async_reg plus async-reset metadata to an
- // unclocked first-stage primitive on EF2; synchronous reset avoids that
- // unsafe mapping while preserving two full settling clocks.
- always @(posedge clk) begin
- if (!rst_n)
- rx_sync_pipe <= 2'b11;
- else
- rx_sync_pipe <= {rx_sync_pipe[0], rx_i};
- end
- always @(posedge clk or negedge rst_n) begin
- if (!rst_n) begin
- state <= ST_IDLE;
- bit_counter <= {COUNTER_BITS{1'b0}};
- bit_index <= 3'd0;
- data_reg <= 8'd0;
- byte_valid <= 1'b0;
- byte_data <= 8'd0;
- framing_error <= 1'b0;
- end else begin
- byte_valid <= 1'b0;
- framing_error <= 1'b0;
- case (state)
- ST_IDLE: begin
- if (!rx_sync_pipe[1]) begin
- bit_counter <= HALF_LAST;
- state <= ST_START;
- end
- end
- ST_START: begin
- if (bit_counter == 0) begin
- if (!rx_sync_pipe[1]) begin
- bit_index <= 3'd0;
- bit_counter <= BIT_LAST;
- state <= ST_DATA;
- end else begin
- state <= ST_IDLE;
- end
- end else begin
- bit_counter <= bit_counter - 1'b1;
- end
- end
- ST_DATA: begin
- if (bit_counter == 0) begin
- data_reg[bit_index] <= rx_sync_pipe[1];
- bit_counter <= BIT_LAST;
- if (bit_index == 3'd7) begin
- state <= ST_STOP;
- end else begin
- bit_index <= bit_index + 1'b1;
- end
- end else begin
- bit_counter <= bit_counter - 1'b1;
- end
- end
- ST_STOP: begin
- if (bit_counter == 0) begin
- state <= ST_IDLE;
- if (rx_sync_pipe[1]) begin
- byte_data <= data_reg;
- byte_valid <= 1'b1;
- end else begin
- framing_error <= 1'b1;
- end
- end else begin
- bit_counter <= bit_counter - 1'b1;
- end
- end
- default: state <= ST_IDLE;
- endcase
- end
- end
- endmodule
|