// UART transmitter, 8N1: 1 start bit (0), 8 data bits LSB first, 1 stop bit (1). // Handshake: the byte on tx_data is accepted on a clock edge where // tx_valid and tx_ready are both high. `timescale 1ns / 1ps module uart_tx #( parameter int CLK_FREQ = 100_000_000, // system clock in Hz parameter int BAUD = 115_200 // bit rate in bits per second ) ( input logic clk, input logic rst, // synchronous, active high input logic [7:0] tx_data, input logic tx_valid, output logic tx_ready, // high while idle output logic txd // serial output, idles high ); // Clock cycles per bit, rounded to the nearest integer. localparam int CLKS_PER_BIT = (CLK_FREQ + BAUD / 2) / BAUD; localparam int CW = $clog2(CLKS_PER_BIT + 1); typedef enum logic [1:0] {S_IDLE, S_START, S_DATA, S_STOP} state_t; state_t state; logic [CW-1:0] baud_cnt; // counts clock cycles within one bit logic [2:0] bit_idx; // which data bit is being sent logic [7:0] shreg; // data bits still to send logic bit_done; // last cycle of the current bit assign bit_done = (baud_cnt == CW'(CLKS_PER_BIT - 1)); assign tx_ready = (state == S_IDLE); // Baud counter: runs while a frame is being sent, wraps every bit. always_ff @(posedge clk) begin if (rst || state == S_IDLE || bit_done) baud_cnt <= '0; else baud_cnt <= baud_cnt + 1'b1; end // Frame FSM. txd is assigned only here, so it comes from a flip-flop // and cannot glitch. always_ff @(posedge clk) begin if (rst) begin state <= S_IDLE; txd <= 1'b1; bit_idx <= 3'd0; shreg <= 8'h00; end else begin case (state) S_IDLE: begin txd <= 1'b1; if (tx_valid) begin shreg <= tx_data; txd <= 1'b0; // start bit state <= S_START; end end S_START: begin if (bit_done) begin txd <= shreg[0]; // data bit 0 shreg <= {1'b0, shreg[7:1]}; bit_idx <= 3'd0; state <= S_DATA; end end S_DATA: begin if (bit_done) begin if (bit_idx == 3'd7) begin txd <= 1'b1; // stop bit state <= S_STOP; end else begin txd <= shreg[0]; shreg <= {1'b0, shreg[7:1]}; bit_idx <= bit_idx + 3'd1; end end end S_STOP: begin if (bit_done) state <= S_IDLE; end default: state <= S_IDLE; endcase end end endmodule