ultrasonic sensor might have a problem

I am using the code below to measure the distance (part of my project) as i did in previous projects. I dont know why but none of my ultrasonic sensors function, they constantly return 0. Is there a way to check if my sensors are faulty or my arduino board?

const int echoPin = 7;
const int trigPin = 6;

float duration , distance;

void setup(){
  Serial.begin(9600);
  pinMode(echoPin,INPUT);
  pinMode(trigPin,OUTPUT);
}

void loop(){
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(15);
  digitalWrite(trigPin,LOW);
  delayMicroseconds(2000);
  digitalWrite(trigPin,HIGH);
  duration = pulseIn(echoPin,LOW);
  Serial.println(distance);

}

Hi, Use the code here first; we know it works:

http://arduino-info.wikispaces.com/UltraSonicDistance

I have just downloaded the NewPing library and your code now works. However, why in the past when i didnt have the library it was working?

Hello Ionnas,

Based on your question I'm gonna conclude your pretty new at using the Arduino. Libraries are pieces of Arduino code mostly written by hardware developers or manufacturers. and they can be very large pieces of code, with many lines. Basically it tells your Arduino how to deal with the inputs generated by the hardware you connected. It can determine calculations, set outputs, decode a series of inputs and many other things I don't understand. Most of the times if you want to work with certain hardware you call for the Library at the beginning of the code where your gonna need it. You can even make your own Libraries. If a piece of code is something you use very often, then create a Library containing that piece of code. Remember, Arduino is open source, so sharing your Library is highly appreciated. When somebody else then wants to use your code, they just install the Library and call upon it in their code.

With Regards,

Mike

Your code is incorrect. The HC-SR04 sends out it's sound pulse after "digitalWrite(trigPin,LOW)" and you have a two second delay while the sensor is returning the measurement on "echoPin". Also "echoPin" is active high and you're looking for low.

Your loop should look something like this:

void loop(){
  digitalWrite(trigPin, HIGH); 
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH, timeout);
  Serial.println(distance);
  delayMicroseconds(2000);
}