module top_ultrason_uart(
    input wire clk,
    input wire start,
    inout wire sig,
    output wire tx
);

    parameter CLK_FREQ = 27_000_000;
    parameter BAUD_RATE = 115_200;
    localparam BIT_PERIOD = CLK_FREQ / BAUD_RATE;

    // Paramètres pour le capteur à ultrasons
    wire [15:0] distance;
    wire [2:0] state_sensor;

    // Signaux pour l'UART TX
    reg [15:0] tx_data;
    reg tx_start = 0;

    // Instance du capteur à ultrasons
    ultrasonic_fpga #(
        .CLK_FREQ(CLK_FREQ)
    ) sensor_inst (
        .clk(clk),
        .start(start),
        .sig(sig),

        .distance(distance),
        .state(state_sensor)
    );

    // Instance de l'UART TX
    uart_tx #(
        .CLK_FREQ(CLK_FREQ),
        .BAUD_RATE(BAUD_RATE)
    ) tx_instance (
        .clk(clk),
        .start(tx_start),
        .data(tx_data[7:0]),

        .tx(tx)
    );

    reg [31:0] wait_counter;
    reg [1:0] state;
    localparam WAIT_NEXT_CYCLES = (CLK_FREQ / 1000) * 100; // 60 ms

    localparam START    = 2'd0;
    localparam WAIT     = 2'd1;

    always @(posedge clk) begin
        case(state)
            START:begin
                if (state_sensor == 3'd6) begin // Lorsque la mesure est terminée, préparer les données
            
                    tx_data <= distance;
                    tx_start <= 1;
                    
                    state <= WAIT;
                end                   
            end

            WAIT:begin
                tx_start <= 0;
                wait_counter <= wait_counter + 1;
                if (wait_counter >= WAIT_NEXT_CYCLES) begin
                    state <= START;
                    wait_counter <= 0;
                end
            end
        endcase
    end

endmodule