Ultrasonic sensor HC-SRO4 giving 0 distance whenever I tried to test the sensor with arduino

Hi all,

I need a big help. I am new to Arduino and trying with a Ultrasonic sensor for my school project.

I used below code and did the wiring correctly, but it give Distance 0 all the time, then I bought a new sensor after tried so many with my existing sensor, but same issue is there with the new sensor too. And when tested from a shop even my old sensor works there.

Can't identify what is wrong with the below code or is there anything to do with IDE version? I have no clue how to fix.
I tried to find in the other posts too...But still struggling.


const int trigPin = 9;
const int echoPin = 10;

long duration;
long distance;


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

void loop() {  

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH, 1);
  distance =  duration*0.034/2;
  Serial.print("Distance : ");
  Serial.print(distance);
  Serial.println(" cm ");
  delay(500);
}

Much appreciate your help on this.

The timeout for your call to pulseIn() seems to be too low.
You are giving it 1 microsecond.
Try the following instead, which will use default timeout of 1 second (1,000,000 microseconds):

duration = pulseIn(echoPin, HIGH);

, or try with some higher value:

duration = pulseIn(echoPin, HIGH, 100000);
1 Like

The @breadboard_led is wright, the value is very, very low.
See your code running ok here with value 30000.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.