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 ?