
module UartTest 
(
  input clk, 
  input rx_pin, 
  output tx_pin 
  );


  // state machine states
  localparam ST_IDLE = 0;
  localparam ST_GOTOIDLE = 1;
  localparam ST_GETVERSION = 2;
  localparam ST_GETVERSIONDATA = 3;

  // FPGA version
  localparam VERSION = "b";


  // UART interface
  wire [7:0]uart_rx_data;
  reg [7:0] uart_tx_data;
  reg uart_strobe_tx_send = 0;
  reg uart_clear = 0;
  reg uart_fifo_rd_pop = 0;
  wire uart_rd_fifoempty; // unused
  wire uart_fifo_wr_full; // unused

  // general
  reg [7:0] state = ST_IDLE;


// Instantiate modules
  UartRxTop #(.FIFOSIZE(32))  UartRxTop_inst 
  (
  	.clk(clk) ,	                            
    .fifo_rd_pop(uart_fifo_rd_pop),
    .rx_pin(rx_pin),
    .clear(uart_clear),
    .fifo_rd_pop_data(uart_rx_data),      // data to be read (from fifo_rd)
    .fifo_rd_empty(uart_rd_fifoempty)     // fifo_rd empty signal 
  );


  UartTxTop #(.FIFOSIZE(16)) UartTxTop_inst
  (
  	.clk(clk) ,	                                // input  clk_sig
  	.fifo_wr_push_data(uart_tx_data) ,	        // input [7:0] fifo_wr_push_data_sig
  	.fifo_wr_push(uart_strobe_tx_send) ,	      // input  fifo_wr_push_sig
    .clear(uart_clear),
  	.fifo_wr_full(uart_fifo_wr_full) ,	        // output  uart_fifo_wr_full
  	.tx_pin(tx_pin) 	                          // output  tx_pin_sig
  );



// -------------------- command interpreter ------------------ 

  always @(posedge clk) begin
    if (uart_fifo_rd_pop == 0) begin
      case (state)
        ST_IDLE:
        begin
          uart_strobe_tx_send <= 0;
            
          if (!uart_rd_fifoempty) begin
            case (uart_rx_data)
              "V": state <= ST_GETVERSION;

              default: begin
                state <= ST_GOTOIDLE;
              end
            endcase          
            uart_tx_data <= uart_rx_data;
            uart_fifo_rd_pop <= 1;
            uart_strobe_tx_send <= 1;
          end  
        end

        ST_GOTOIDLE:
        begin
          state <= ST_IDLE;
        end  

        // send FPGA version byte
        ST_GETVERSION:
        begin
          uart_strobe_tx_send <= 0; 
          state <= ST_GETVERSIONDATA;
        end  

        ST_GETVERSIONDATA:
        begin
          uart_tx_data <= VERSION;
          uart_strobe_tx_send <= 1;
          state <= ST_IDLE;
        end  

        default:
        begin
          state <= ST_IDLE;
          uart_fifo_rd_pop <= 1;
        end
      endcase
    end
    else begin
      uart_fifo_rd_pop <= 0;
    end        
  end  

endmodule