module UartTx (
  input clk,                // system clock
  input uart_clk,           // uart valid clock (mask for system clock)
  input [7:0] tx_data_in,   // data to be sent
  input tx_data_valid,      // tx_data_in are ready to be sent 
  output is_ready_to_send,  // module is ready for new data
  output reg tx_pin             // serial output data 
  ); 

  localparam WAITFORDATA = 0;
  localparam WRITESTARTBIT = 1;
  localparam WRITEDATABITS = 2;
  localparam WRITESTOPBIT = 3;

  reg [3:0] bitcount;
  reg sending = 0;
  reg [7:0]tx_data = 8'h47;    
  reg [1:0] state = WAITFORDATA;


  always@(posedge clk) begin
    case (state)
      WAITFORDATA: begin
        tx_pin <= 1;
        if (tx_data_valid) begin
          tx_data <= tx_data_in;
          sending <= 1;
          bitcount <=0;
          if (uart_clk) begin
            state <= WRITESTARTBIT;
          end  
        end
      end

      WRITESTARTBIT: begin
        if (uart_clk) begin
          tx_pin <= 0; // start bit
          state <= WRITEDATABITS;
        end  
      end

      WRITEDATABITS: begin
        if (uart_clk) begin
          tx_pin <= tx_data[bitcount];
          bitcount <= bitcount + 4'd1;
          if (bitcount == 7) begin
            state <= WRITESTOPBIT;
          end  
        end  
      end  
      WRITESTOPBIT: begin
        if (uart_clk) begin
          tx_pin <= 1; // stop bit
          sending <= 0;
          state <= WAITFORDATA;
        end  
      end  
    endcase
  end

  assign is_ready_to_send = ~sending;
  
endmodule