HC-SR04 UltraSound distance Sensor Arduino/esp32

To increase the precision of a sensor reading in arduino ( in this example the cheapo HC-SR04 distance sensor ) you can temporarily disable interrupts during reading of the sensor.



noInterrupts();
duration = pulseIn(echoPin, HIGH);
interrupts();


In the case of this sensor, you can also read it more times ( I take 5 measurements ) and get only the middle value,
the mostly complete example would be something like this



        for (int i=0; i < 5; i++ ) {
            unsigned long current_distance = 0;
            digitalWrite(triggerPin, LOW);
            delayMicroseconds(6);
            digitalWrite(triggerPin, HIGH);
            delayMicroseconds(10);
            digitalWrite(triggerPin, LOW);

            noInterrupts();
            current_distance = pulseIn(echoPin, HIGH);// Reads the echoPin, returns the sound wave travel time in microseconds;
            interrupts();

            distances[i] = current_distance;
        }
        for (int i = 1; i < 5; i++) {
            unsigned long key = distances[i];
            int j = i - 1;
            while (j >= 0 && distances[j] > key) {
                distances[j + 1] = distances[j];
                j = j - 1;
            }
            distances[j + 1] = key;
        }
        // Calculate the distance
        // 0.03433 sound speed in air in centimeters/microseconds
        distanceCm = distances[2]  * 0.03433 / 2;


Sources:

https://projecthub.arduino.cc/Isaac100/getting-started-with-the-hc-sr04-ultrasonic-sensor-7cabe1
https://playwithcircuit.com/ultrasonic-sensor-hc-sr04-interfacing-with-arduino/
https://projecthub.arduino.cc/panagorko/next-level-ultrasonic-sensor-df5768