How to make an ultrasonic sensor more accurate and consistent?

Hi!
I have a problem with my HC-SR04 ultrasonic sensors in that the variation of the sensor is about 20 percent. That is much too steep for me. I was wondering if there is something I can do either by programming or by hardware solution to lower the variation of the readings? I have been taking the average of like ten readings but that doesn’t seem to help much. Here is the current code:

#include <NewPing.h>

#define TRIGGER_PIN  12  
#define ECHO_PIN     11  
#define MAX_DISTANCE 200 
int total;
int pin;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
// NewPing setup of pins and maximum distance.
void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  int final = 20;
  int myInts[20];
  for (int pin = 0; pin < 20; pin++) {
  unsigned int uS = sonar.ping();
  myInts[pin]=uS;
  delay(100);
  
  }
  for (int i=0; i<20;i++){
    if (myInts[i] > 1500){
        total = total + myInts[i];
        
    }
    else{
      final = final -1;
    }
  
  }
  total = total/final;
}

Any help would be greatly appreciated!

Post your actual code, but use code tags.

Groove:
Post your actual code, but use code tags.

The above code is the whole void loop(). I also edited to have the right tags :slight_smile:

And "total" is. . .. ?

Post your code.
All of it.

Groove:
And "total" is. . .. ?

Post your code.
All of it.

Updated

So, where do you zero total?

BTW, when I say "post your code", I really, really mean it.

Groove:
So, where do you zero total?

BTW, when I say “post your code”, I really, really mean it.

I did post all of the code, nothing is left out. I see I made a very obvious mistake of not zeroing out the total. That explains a lot of things! Thanks!

The NewPing library includes an averaging option. Have you tried it?