module ultrasonic_fpga #(
    parameter integer CLK_FREQ = 27_000_000  // frequence de clk en Hz
)(
    input wire clk,
    input wire rst,
    input wire start,           // signal de declenchement 
    input wire echo,            // retour du capteur
    output reg trig_out,        // signal envoye au capteur
    output reg [8:0] distance  // distance mesuree
);

    reg [2:0] state;
    reg [8:0] trig_counter;
    reg [15:0] echo_counter;

    localparam IDLE = 0, TRIG = 1, WAIT_ECHO = 2, MEASURE_ECHO = 3, DONE = 4;

    // Constantes dépendantes de CLK_FREQ
    localparam integer TRIG_DURATION_CYCLES = CLK_FREQ / 100_000; // 10us
    localparam integer DIST_DIVISOR = (58 * CLK_FREQ) / 1_000_000; // pour conversion µs -> cm

    always @(posedge clk or posedge rst) begin
        if (rst) begin
            state <= IDLE;
            trig_out <= 0;
            trig_counter <= 0;
            echo_counter <= 0;
            distance <= 0;
        end else begin
            case (state)
                IDLE: begin
                    if (start) begin
                        state <= TRIG;
                    end
                end

                TRIG: begin
                    if (trig_counter < TRIG_DURATION_CYCLES) begin
                        trig_out <= 1;
                        trig_counter <= trig_counter + 1;
                    end else begin
                        trig_out <= 0;
                        trig_counter <= 0;
                        state <= WAIT_ECHO;
                    end
                end

                WAIT_ECHO: begin
                    if (echo) begin
                        echo_counter <= 0;
                        state <= MEASURE_ECHO;
                    end
                end

                MEASURE_ECHO: begin
                    if (echo) begin
                        echo_counter <= echo_counter + 1;
                    end else begin
                        distance <= (echo_counter*1000) / DIST_DIVISOR;
                        state <= DONE;
                    end
                end

                DONE: begin
                    state <= IDLE;
                end
            endcase
        end
    end

endmodule
