Hi, I also have this problem when doing project with HCSR04 sensor.
I tried different codes and different connections but all those did not work.
So I finally figure out it should be the problem with welding on the sensor itself. I tried to press my finger onto certain point of the sensor, then the sensor suddenly begins to produce result, but in a very fast way. ignoring all the delay command I put in the code.
Maybe you can tries to but more HCSR04 sensor and see the result.
Hope this can help you.
The problem is with New Ping doesn't work at all well for AJ-SR04M.
Try this its working fine
/*
AJ-SR04M distance sensor
with Arduino Nano
Echo to Arduino Echo pin 11
Arduino pin 12 Trig
*/
#define trigPin 12
#define echoPin 11
int cnt =0 ;
long rds[10];
void setup() {
Serial.begin (115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distance,distance1;
digitalWrite(trigPin, LOW); // Put trigger pin low
delayMicroseconds(2); // for two microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // for ten microseconds
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); //Default time out I second
distance = (duration/2) / 29.1;
if (distance <= 100 ) // slow rate of change
{
if (cnt >9)
{
cnt =0;
}
rds[cnt] =distance/10; //
distance1= rds[1]+rds[2]+rds[3]+rds[4]+rds[5]+rds[6]+rds[7]+rds[8]+rds[9]+rds[0];
Serial.print(distance1);
Serial.println(" cm");
cnt++;
}
delay(50);
}
Best,
I also faced the same problem a few hours ago after reading all the posts in the forum and found an alternate way they maybe help someone. instead of jumper cables and breadboard I directly soldered the wires to my Arduino mega and Molex connector to ultrasonic sensor now it is completely working fine.