Trouble with ultrasonic sensor hc-sr04

Hi,

I have problems with ultrasonic sensor hc-sr04 on the UNO and MEGA 2560. I try many times to get it working but it's unstable. It measure correct but it hangs if I turn the sensor, and this is unpredictable. If it hangs I get no readings as only 0 cm, if I hit the sensor a very little bit it start working correct again. I check and re-check the connections many times and change cables and ports but it just hang unpredictable every time. Some times it work for a longer time good, not touching the sensor, but some times even I not touch the sensor it just hang. I try 4 sensors but all the same. I try different codes incl. NewPing ect., I can not belief all the sensors are bad unless I'm just bad luck and get from a wrong series. See below just a simple code;

// HC-SR04 Sensor const int trigPin = 12; const int echoPin = 11;

void setup() { Serial.begin(9600); } void loop(){ long duration, 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(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);

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

Serial.print(cm); Serial.print("cm"); Serial.println(); delay(60); } long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; }

Who has the same experience and a possible solution for this problem ?

Sounds like marginal timing or a loose connection. Since the HC-SR04 sells for under $2 it might easily be a bad connection in the HC-SR04. Check the soldering.

Unlike the older PING)))™ sensor the HC-SR04 has separate Trigger (output) and Echo (input) pins. That means you can initialize the pin direction in setup() instead of in the middle of your sketch.

This simplifies the sketch a bit:

// HC-SR04 Sensor
const int trigPin = 12;
const int echoPin = 11;

void setup() {
  Serial.begin(9600);

  digitalWrite(trigPin, LOW);
  pinMode(trigPin, OUTPUT);

  pinMode(echoPin, INPUT);
}

void loop() {
  unsigned long duration;
  unsigned int 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:

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.println(" cm");
  delay(500);
}

long microsecondsToCentimeters(unsigned long microseconds)
{
  return microseconds / 29 / 2;
}