uart_rx.v 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. `timescale 1ns/1ps
  2. // 8-N-1 UART receiver.
  3. // RX input is first synchronized into clk domain.
  4. module uart_rx #(
  5. parameter integer CLK_HZ = 25000000,
  6. parameter integer BAUD = 115200
  7. )(
  8. input wire clk,
  9. input wire reset_n,
  10. input wire rx,
  11. output reg [7:0] data,
  12. output reg valid,
  13. output reg framing_error
  14. );
  15. localparam integer CLKS_PER_BIT = CLK_HZ / BAUD;
  16. localparam integer HALF_BIT = CLKS_PER_BIT / 2;
  17. localparam [1:0] R_IDLE = 2'd0;
  18. localparam [1:0] R_START = 2'd1;
  19. localparam [1:0] R_DATA = 2'd2;
  20. localparam [1:0] R_STOP = 2'd3;
  21. reg rx_meta;
  22. reg rx_sync;
  23. reg [1:0] state;
  24. reg [15:0] clk_count;
  25. reg [2:0] bit_index;
  26. reg [7:0] data_shift;
  27. always @(posedge clk or negedge reset_n) begin
  28. if (!reset_n) begin
  29. rx_meta <= 1'b1;
  30. rx_sync <= 1'b1;
  31. end else begin
  32. rx_meta <= rx;
  33. rx_sync <= rx_meta;
  34. end
  35. end
  36. always @(posedge clk or negedge reset_n) begin
  37. if (!reset_n) begin
  38. state <= R_IDLE;
  39. clk_count <= 16'd0;
  40. bit_index <= 3'd0;
  41. data_shift <= 8'd0;
  42. data <= 8'd0;
  43. valid <= 1'b0;
  44. framing_error <= 1'b0;
  45. end else begin
  46. valid <= 1'b0;
  47. framing_error <= 1'b0;
  48. case (state)
  49. R_IDLE: begin
  50. clk_count <= 16'd0;
  51. bit_index <= 3'd0;
  52. if (!rx_sync)
  53. state <= R_START;
  54. end
  55. R_START: begin
  56. // Sample around the middle of the start bit to reject a short glitch.
  57. if (clk_count == HALF_BIT - 1) begin
  58. clk_count <= 16'd0;
  59. if (!rx_sync)
  60. state <= R_DATA;
  61. else
  62. state <= R_IDLE;
  63. end else begin
  64. clk_count <= clk_count + 1'b1;
  65. end
  66. end
  67. R_DATA: begin
  68. if (clk_count == CLKS_PER_BIT - 1) begin
  69. clk_count <= 16'd0;
  70. data_shift[bit_index] <= rx_sync;
  71. if (bit_index == 3'd7) begin
  72. bit_index <= 3'd0;
  73. state <= R_STOP;
  74. end else begin
  75. bit_index <= bit_index + 1'b1;
  76. end
  77. end else begin
  78. clk_count <= clk_count + 1'b1;
  79. end
  80. end
  81. R_STOP: begin
  82. if (clk_count == CLKS_PER_BIT - 1) begin
  83. clk_count <= 16'd0;
  84. if (rx_sync) begin
  85. data <= data_shift;
  86. valid <= 1'b1;
  87. end else begin
  88. framing_error <= 1'b1;
  89. end
  90. state <= R_IDLE;
  91. end else begin
  92. clk_count <= clk_count + 1'b1;
  93. end
  94. end
  95. default: state <= R_IDLE;
  96. endcase
  97. end
  98. end
  99. endmodule