Arduino Ultra Sonic Sensor always returns 0

ianaya89 picture ianaya89 · Jun 29, 2015 · Viewed 16.4k times · Source

I am doing a basic project in Arduino UNO connecting an Ultra Sonic sensor (HC-SR04) which should print in the serial monitor the distance of the closest object but it always print 0.

This is my code:

long distance;
long time;

void setup(){
  Serial.begin(9600);
  pinMode(4, OUTPUT); 
  pinMode(2, INPUT); 
}

void loop(){
  digitalWrite(2,LOW);
  delayMicroseconds(5);
  digitalWrite(2, HIGH);
  delayMicroseconds(10);

  time = pulseIn(4, HIGH);
  distance = int(0.017*time); 

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm.");
  delay(1000);
}

And this is the breadboard:

enter image description here

Answer

embedded_guy picture embedded_guy · Jun 30, 2015

The primary issue that I see is that your code doesn't match your wiring diagram.

For example, your diagram shows Trig connected to pin 4. The Trig should be the output from your Arduino but you have it defined as an input.

The Echo is connected to pin 2 and it should be an input, but you have it defined as an output.

Finally, in your loop(), you are not even using pin 2 or pin 4, but pins 9 and 8. Another issue is the timing you use in setting the trigger pulse - it does not match the datasheet. I would do something like this (assuming that you are actually connected to the pins shown in your diagram):

#define sensorTrigPin    4
#define sensorEchoPin    2

void setup()
{
    Serial.begin(9600);
    pinMode(sensorTrigPin, OUTPUT);
    pinMode(sensorEchoPin, INPUT);
}

void loop()
{
    int pulseWidth = 0;

    digitalWrite(sensorTrigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(sensorTrigPin, LOW);

    pulseWidth = pulseIn(sensorEchoPin, HIGH);

    Serial.print("Pulse Width: ");
    Serial.print(pulseWidth);
    delay(1000);
}

Note that pulseWidth is just the amount of time that it takes from the beginning of the Echo pulse going high to the end of the same pulse (when it goes low). You would still have to calculate the distance based on the value of pulseWidth.


UPDATE BASED ON RECENT EDIT TO THE QUESTION

If you change a portion of your loop() code to this, it should work:

void loop(){
    digitalWrite(4, HIGH);   //was (2, LOW)
    delayMicroseconds(10);   //was (5)
    digitalWrite(4, LOW);    //was (2, HIGH)
    //REMOVED EXTRA DELAY

    time = pulseIn(2, HIGH);  //was (4,HIGH);
    ...  //Keep the rest of your code the same.
}