Hello Tim,
Thanks for your clarifications. I followed your instructions and modified your excellent code so readings are in millimeters.
To avoid using Float numbers I simply use millimeters in the US_ROUNDTRIP_MM value.
Since some readings are Zero when they shouldn't be (in my case they can never be zero), I exclude those readings.
I also average 5 consecutive readings so the calculated distance is more stable.
I am attaching your modified code in case someone else is interested.
Thanks again for your excellent code and your help!
// ---------------------------------------------------------------------------
// Example NewPing library sketch that calculates distance in MILLIMETERS
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 2 // ESP32 pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 5 // ESP32 pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 2000 // Maximum distance we want to ping for (in millimeters). Maximum sensor distance is rated at 4000-5000mm.
#define US_ROUNDTRIP_MM 5650 // Roundtrip sound speed mm/microseconds (In my case 5650 gave me most accurate distance)
int d;
int d1;
int i = 0;
int daverage = 0; // average of 5 sonar.ping() readings
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings. 29ms should be the shortest delay between pings.
Serial.println("Ping: ");
i = 1;
while (i <= 5) {
d = sonar.ping();
if (d == 0) d = sonar.ping();
daverage = daverage + d;
i++;
}
d=daverage/5;
daverage = 0;
Serial.print (" Average ping time in microseconds = ");
Serial.println (d);
d1 = ((1000*d / US_ROUNDTRIP_MM)); // Calculate Distance in mm
Serial.print("Distance = ");
Serial.print(d1); // Print distance in m
Serial.println("mm ");
Serial.println(" ");
delay(1000); // Wait 1 second until next reading (can be zero or any other number)
}