I have a short sketch for a D1 mini which uses the ultrasound board HC-SR04 to measure a distance.
As the measurements are rather unstable (for example varying between 7 and 15 for a 14cm distance) I thought to always do 10 measurements and calculate the average.
What I don't get now is: from 10 measurements my total is 149. When I divide this by 10, I get 14. But with proper rounding this should come as 15.
Here my code:
int checkDistance() {
long duration;
int distance;
int distance_inc;
distance = 0;
// make 10 measurements and add up all values
for (int i = 0; i < 10; i++) {
// send trigger to HC-SRD4
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// measure the duration between the trigger and the return of the signal in micro-seconds
duration = pulseIn(echoPin, HIGH);
// calculate the distance in cm
// deduct 9cm to get reference level 0
// distance = (duration * 0.034 / 2) - 9;
// or without bias:
distance_inc = (duration * 0.034 / 2);
distance = distance + distance_inc;
Serial.printf("increment: %i\n", distance_inc);
Serial.printf("Distance: %i\n", distance);
delay(100);
}
distance = round(distance / 10); // get average of 10 measurements
return distance;
}
From a mathematical point of view this doesn't make sense as you telling me to distort the measurement. Hence I wasn't sure what you mean.
But what you are essentially telling me is, yes the rounding doesn't work the way as expected but there is a tweak around it.
However, @UKHeliBob's comment was helpful. Thanks, now it works.