Spikes using HC-sr04

Hello,

I am using HC-sr04 with Boron to measure distance between 6 cm to 14cm, it works but i get spikes as you can see from the attached picture , known that the object is not moving as i left it at night and this morning i found these spikes, any idea how to eliminate them? i have increased the trig pin microsounds to 10 trying to give more time for the echo not to confuse from previous reading but still i see these spikes.

i use this code:

void loop()
{

    float duration, inches, cm;

  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
   delayMicroseconds(15);
  digitalWrite(trigPin, LOW);


  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print("\t");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
}

float microsecondsToInches(float microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.

  return microseconds / 74.00 / 2.0;
}

float microsecondsToCentimeters(float microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29.00 / 2.0;
}

Thank you in advance for your help

spikes_1

You would not need to set the pinMode() each iteration of loop but only once in setup().
You may also want to limit your calculation when microseconds is non-zero as this could indicate the case that no ping was received.
You should also be aware that you may well receive stray echoes or even surrounding noise may trigger the input (e.g. my car’s parking sensors sometimes trigger when I’m stood at traffic lights next to a HGV for their noise). Hence you may consider some filtering and some extra delays between two measurements (e.g. 50ms).

2 Likes

Interrupt latency will also be a factor on Gen 3 devices, even using pulseIn(). I ended up writing the JSN-SR04_Gen3_RK library which uses the nRF52 I2S (sound IO) hardware peripheral to more accurately measure the pulses. It’s also non-blocking.

3 Likes