
module uart ( input CLK, input RESET, input TX_SIGNAL, input [7:0] TX_BYTE,
              output TX_ACTIVITY, output TX_LINE);
//            CLK - INPUT CLOCK (12 MHZ FOR ICESTICK), RESET: IF RESET == 0, MODULE RESETS
//            TX_SIGNAL - SIGNAL TO START TRANSMISSION (RISING EDGE), TX_BYTE - BYTE TO TRANSMIT
//            TX_ACTIVITY = 1, IF SOME BYTE IS TRANSMITTING NOW, ELSE - 0
//            TX_LINE - LINE OF UART_TX,
//            IF BYTE IS TRANSMITTING, ATTEMPT TO TRANSMIT OTHER BYTE HAS NO EFFECT
//            MODULE WORKS AT POSEDGE

parameter CLK_DIV = 13;   //  921600
//parameter CLK_DIV = 5000; //  2400
//parameter CLK_DIV = 104; //  115200
reg TX_sig_last;
reg [3:0] tx_bit_counter;
reg [3:0] tx_clk_counter; //  MUST CONTAIN CLK DIV
//reg [7:0] tx_data;
reg tx_activity;
reg tx_line;
initial begin
  TX_sig_last = 0;
  tx_line = 1;
end

always @ (negedge CLK) begin
  if (RESET == 0) begin
    /*tx_data = 0;*/  //tx_clk_counter = 0;
    tx_activity = 0;
  end

  else begin
    if (tx_activity)  begin
      tx_clk_counter = tx_clk_counter - 1;
      if (tx_clk_counter == 0)  begin
        tx_clk_counter = CLK_DIV;
        if (tx_bit_counter == 0)
          tx_activity = 0;
        else  begin
          tx_bit_counter = tx_bit_counter - 1;
          if (tx_bit_counter > 0)
            tx_line = TX_BYTE[8-tx_bit_counter];
          else
            tx_line = 1;  //  STOP_BIT
        end
      end
    end
    else  begin
      if ((TX_SIGNAL == 1) && (TX_sig_last == 0)) begin
        //tx_data = TX_BYTE;
        tx_activity = 1;
        tx_bit_counter = 9;  //  NO PARITY, STOP 1 BIT
        tx_clk_counter = CLK_DIV;
        tx_line = 0;  //  START BIT
      end
    end
    TX_sig_last = TX_SIGNAL;
  end
end

assign TX_LINE = tx_line;
assign TX_ACTIVITY = tx_activity;

endmodule
