I just received my HC-SR04 from Hong-Kong and I am having trouble getting it to work with my ATMega2560. The ATMega2560 is connected to my laptop via USB, and the HC-SR04 is using 5V and ground from the Arduino for power. I have the trigger connected to Pin 2 and the echo to pin 3. I have the Ultrasonic library downloaded from ITead and I changed their example a little bit because I don't have an LCD.
I have tried both of the following code, and in both cases I get nothing but "0 CM" being printed to the serial monitor.
double ping(int outPin, int inPin) //Get CM to obstacle in front of the sensor
{
long duration;
pinMode(outPin, OUTPUT);
pinMode(inPin, INPUT);
digitalWrite(outPin, LOW);
delayMicroseconds(2);
digitalWrite(outPin, HIGH);
delayMicroseconds(10);
digitalWrite(outPin, LOW);
delayMicroseconds(10);
duration = pulseIn(inPin, HIGH);
return duration / 29.0 / 2.0;
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(ping(2, 3)); Serial.println("cm");
delay(500);
}
I read that sometimes people have an issue with the HC-SR04 if you start it up with nothing out in front of it to echo. I tried with and without a barrier in front and both ways I still only get "0 CM" on the monitor.
Does anyone have any ideas on what I may be doing wrong? Also is there any way to test the HC-SR04 to know if it is defective?
Please let me know if I need to provide any additional info.
I returned the first HC-SR04 and the ebay seller from Hong Kong sent me a second one to try. The new one works great and I can say that both versions of the code above will work with the HC-SR04.
On the face of it, it looks like a cheap knock-off of Devantech's device (It has a two pin interface with "trig" and "echo"), but the example code looks more like it is a cheap knock-off of the Ping sensor, with a single pin interface.
I don't have one, so I'm going to remain confused.
.cpp:1:24: error: Ultrasonic.h: No such file or directory
:1: error: 'Ultrasonic' does not name a type
.cpp: In function 'void loop()':
:10: error: 'ultrasonic' was not declared in this scope
:10: error: 'CM' was not declared in this scope