/**
 * UartTX controls transmission of bytes over UART.
 *
 * When load = 1 the chip starts serial transmission of the byte in[7:0] to the
 * TX line according to the protocoll 8N1 with 115200 baud. During transmission
 * out[15] is set to high (busy). The transmission is finished after 2170 clock 
 * cycles (10 byte a 217 cycle each). When transmission completes out[15] goes
 * low again (ready). 
 */
`default_nettype none
module UartTX (
    input wire clk,
    input wire load,
    input wire [15:0] in,
    output wire TX,
    output reg [15:0] out
);

    reg [9:0] baud_count;
    reg [3:0] bit_index;
    reg [9:0] shift_reg;
    reg tx_active;

    initial begin
        tx_active <= 1'b0;
        shift_reg <= 10'b1;
    end


    always @(posedge clk) begin
        // Output status
        out <= (load || tx_active) ? 16'h8000 : 16'h0000;

        if (!tx_active && load) begin
            // Load start bit + data + stop bit into shift register
            shift_reg <= {1'b1, in[7:0], 1'b0}; // {stop, data[7:0], start}
            tx_active <= 1;
            baud_count <= 0;
            bit_index <= 0;
        end else if (tx_active) begin
            if (baud_count == 216) begin
                baud_count <= 0;
                bit_index <= bit_index + 1;
                shift_reg <= {1'b1, shift_reg[9:1]}; // shift in stop bit after final bit
                if (bit_index == 9) begin
                    tx_active <= 0;
                    out <= 16'h0000;
                end
            end else begin
                baud_count <= baud_count + 1;
            end
        end
    end

    assign TX = shift_reg[0];

endmodule
