`timescale 1ns/1ps

module tb_ultrasonic_fpga;

    reg clk = 0;
    reg rst = 1;
    reg start = 0;
    reg echo = 0;
    wire trig_out;
    wire [8:0] distance;

    time t_start, t_end;

    // Clock 27MHz => periode = 37ns
    always #18 clk = ~clk;

    ultrasonic_fpga uut (
        .clk(clk),
        .rst(rst),
        .start(start),
        .echo(echo),
        .trig_out(trig_out),
        .distance(distance)
    );

    initial begin
        $dumpfile("ultrasonic.vcd");
        $dumpvars(0, tb_ultrasonic_fpga);

        // Reset
        #100;
        rst = 0;

        // Start
        #100;
        start = 1;
        #40;
        start = 0;

        wait (trig_out == 1);
        t_start = $time;

        // Attendre qu'il redescende
        wait (trig_out == 0);
        t_end = $time;

        $display("Trig HIGH duration: %0dns", t_end - t_start);

        if ((t_end - t_start) >= 9500 && (t_end - t_start) <= 10500) begin
            $display("Trigger signal is high for 10us.");

            #10;
            echo = 1;

            #5800;// Echo dure 5800ns (≈ 100 cycles @ 27MHz => ≈ 100 cm aller-retour)
            echo = 0;
        end else begin
            $display("Trigger signal is NOT high for 10us.");
        end

        #500;

        // Affiche la distance
        if (distance > 0) begin
            $display("Distance measured: %d cm", distance);
        end else begin
            $display("No distance measured.");
        end

        $finish;
    end

endmodule
