Arduino Ultra Sonic Sensor always returns 0

I am doing a basic project in Arduino UNO connecting an Ultra Sonic sensor (HC-SR04) that should print the distance of the nearest object on the serial monitor, but it always prints 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 layout:

enter image description here

+3


source to share


2 answers


The main problem I see is that your code doesn't match your wiring diagram.

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

The echo connects to pin 2 and it should be an input, but you define it as an output.

Finally, in yours, loop()

you don't even use pin 2 or pin 4, but pins 9 and 8. Another problem is the time you use when setting up the trigger pulse - it is out of specification. I would do something like this (assuming you are actually connected to the pins shown in the 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

- this is simply the amount of time it takes from the start of an Echo pulse going high to the end of the same pulse (when it goes low). You will still have to calculate the distance based on the value pulseWidth

.


UPDATE BASED ON LAST CHANGES TO THE QUESTION

If you change part of your code loop()

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.
} 

      

+2


source


Try connecting the VCC of the sensor to 3V3 instead of 5V. It may sound strange, but I tried it and it worked. Also, make sure your echo and trigger match the code.



0


source







All Articles