HC-SR04 Ultrasonic sensor gives weird readings

Hello everybody,

I recently purchased a new sensor for my Arduino. It is the HC-SR04 ultrasonic sensor. I immediately started testing it out and it worked just great. It was able of reading objects at like 2m in front of the sensor. Just as I expected it to work.

However, when I started the exact same program (wires also remained the same), it gave me false readings. It could no longer detect objects beyond 7cm.

Any ideas on how to solve this issue? I am using the NewPing library. Also, I do not think my sensor is broken, since I was able to read from it successfully yesterday.

The board I am using for testing is the Arduino Mega 2560 R3.

This is the code I am using:

#include <NewPing.h>

#define TRIGGER_PIN 4
#define ECHO_PIN 2
#define MAX_DISTANCE 500
#define PING_AMOUNT 25
#define PING_PAUSE 50
 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
 
void setup() {
  // Start the serial monitor
  Serial.begin(115200);
}

void loop() {
  delay(PING_PAUSE);
  // Pick the average out of multiple pings, this increases the overall accuracy
  float resultMicroSeconds = sonar.ping_median(PING_AMOUNT);
  float resultCM = sonar.convert_cm(resultMicroSeconds);

  // Just log the distance to the serial monitor
  Serial.print("Average distance over ");
  Serial.print(PING_AMOUNT);
  Serial.print(" pings: ");
  Serial.print(resultCM);
  Serial.println(" cm.");
}

Any help is appreciated.

Thanks in advance,

Tahar