uart_tx.v 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. `timescale 1ns/1ps
  2. // 8-N-1 UART transmitter.
  3. module uart_tx #(
  4. parameter integer CLK_HZ = 25000000,
  5. parameter integer BAUD = 115200
  6. )(
  7. input wire clk,
  8. input wire reset_n,
  9. input wire start,
  10. input wire [7:0] data,
  11. output reg tx,
  12. output reg busy,
  13. output reg done
  14. );
  15. localparam integer CLKS_PER_BIT = CLK_HZ / BAUD;
  16. localparam [1:0] U_IDLE = 2'd0;
  17. localparam [1:0] U_START = 2'd1;
  18. localparam [1:0] U_DATA = 2'd2;
  19. localparam [1:0] U_STOP = 2'd3;
  20. reg [1:0] state;
  21. reg [15:0] clk_count;
  22. reg [2:0] bit_index;
  23. reg [7:0] data_latched;
  24. always @(posedge clk or negedge reset_n) begin
  25. if (!reset_n) begin
  26. state <= U_IDLE;
  27. clk_count <= 16'd0;
  28. bit_index <= 3'd0;
  29. data_latched <= 8'd0;
  30. tx <= 1'b1;
  31. busy <= 1'b0;
  32. done <= 1'b0;
  33. end else begin
  34. done <= 1'b0;
  35. case (state)
  36. U_IDLE: begin
  37. tx <= 1'b1;
  38. busy <= 1'b0;
  39. clk_count <= 16'd0;
  40. bit_index <= 3'd0;
  41. if (start) begin
  42. data_latched <= data;
  43. busy <= 1'b1;
  44. tx <= 1'b0;
  45. state <= U_START;
  46. end
  47. end
  48. U_START: begin
  49. busy <= 1'b1;
  50. tx <= 1'b0;
  51. if (clk_count == CLKS_PER_BIT - 1) begin
  52. clk_count <= 16'd0;
  53. bit_index <= 3'd0;
  54. tx <= data_latched[0];
  55. state <= U_DATA;
  56. end else begin
  57. clk_count <= clk_count + 1'b1;
  58. end
  59. end
  60. U_DATA: begin
  61. busy <= 1'b1;
  62. tx <= data_latched[bit_index];
  63. if (clk_count == CLKS_PER_BIT - 1) begin
  64. clk_count <= 16'd0;
  65. if (bit_index == 3'd7) begin
  66. tx <= 1'b1;
  67. state <= U_STOP;
  68. end else begin
  69. bit_index <= bit_index + 1'b1;
  70. end
  71. end else begin
  72. clk_count <= clk_count + 1'b1;
  73. end
  74. end
  75. U_STOP: begin
  76. busy <= 1'b1;
  77. tx <= 1'b1;
  78. if (clk_count == CLKS_PER_BIT - 1) begin
  79. clk_count <= 16'd0;
  80. busy <= 1'b0;
  81. done <= 1'b1;
  82. state <= U_IDLE;
  83. end else begin
  84. clk_count <= clk_count + 1'b1;
  85. end
  86. end
  87. default: state <= U_IDLE;
  88. endcase
  89. end
  90. end
  91. endmodule