uart_rx_byte_fractional.v 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. `timescale 1ns/1ps
  2. // Candidate-B Host receiver. A phase accumulator schedules 27/28-clock bit
  3. // intervals for 25 MHz / 921600 without a PLL.
  4. module uart_rx_byte_fractional #(
  5. parameter integer CLOCK_HZ = 25000000,
  6. parameter integer BAUD = 921600
  7. ) (
  8. input wire clk,
  9. input wire rst_n,
  10. input wire rx_i,
  11. output reg byte_valid,
  12. output reg [7:0] byte_data,
  13. output reg framing_error
  14. );
  15. localparam [1:0] ST_IDLE = 2'd0;
  16. localparam [1:0] ST_START = 2'd1;
  17. localparam [1:0] ST_DATA = 2'd2;
  18. localparam [1:0] ST_STOP = 2'd3;
  19. (* async_reg = "true" *) reg [1:0] rx_sync_pipe;
  20. reg [1:0] state;
  21. reg [31:0] phase_accumulator;
  22. reg [2:0] bit_index;
  23. reg [7:0] data_reg;
  24. wire [32:0] phase_sum = {1'b0, phase_accumulator} + BAUD;
  25. wire [32:0] clock_hz_extended = {1'b0, CLOCK_HZ[31:0]};
  26. wire [31:0] phase_remainder = phase_sum[31:0] - CLOCK_HZ[31:0];
  27. wire phase_tick = phase_sum >= clock_hz_extended;
  28. always @(posedge clk or negedge rst_n) begin
  29. if (!rst_n) begin
  30. rx_sync_pipe <= 2'b11;
  31. state <= ST_IDLE;
  32. phase_accumulator <= 0;
  33. bit_index <= 0;
  34. data_reg <= 0;
  35. byte_valid <= 0;
  36. byte_data <= 0;
  37. framing_error <= 0;
  38. end else begin
  39. rx_sync_pipe <= {rx_sync_pipe[0], rx_i};
  40. byte_valid <= 0;
  41. framing_error <= 0;
  42. case (state)
  43. ST_IDLE: begin
  44. phase_accumulator <= 0;
  45. if (!rx_sync_pipe[1]) begin
  46. phase_accumulator <= CLOCK_HZ / 2;
  47. state <= ST_START;
  48. end
  49. end
  50. ST_START: begin
  51. if (phase_tick) begin
  52. phase_accumulator <= phase_remainder;
  53. if (!rx_sync_pipe[1]) begin
  54. bit_index <= 0;
  55. state <= ST_DATA;
  56. end else state <= ST_IDLE;
  57. end else phase_accumulator <= phase_sum[31:0];
  58. end
  59. ST_DATA: begin
  60. if (phase_tick) begin
  61. phase_accumulator <= phase_remainder;
  62. data_reg[bit_index] <= rx_sync_pipe[1];
  63. if (bit_index == 7) state <= ST_STOP;
  64. else bit_index <= bit_index + 1'b1;
  65. end else phase_accumulator <= phase_sum[31:0];
  66. end
  67. ST_STOP: begin
  68. if (phase_tick) begin
  69. phase_accumulator <= phase_remainder;
  70. state <= ST_IDLE;
  71. if (rx_sync_pipe[1]) begin
  72. byte_data <= data_reg;
  73. byte_valid <= 1;
  74. end else framing_error <= 1;
  75. end else phase_accumulator <= phase_sum[31:0];
  76. end
  77. default: state <= ST_IDLE;
  78. endcase
  79. end
  80. end
  81. endmodule