Spikes using HC-sr04


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);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);

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

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

  Serial.print("in, ");

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


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).


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.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.