Not sure whether HC-SR04 is broken

Recently, I bought a HC-SR04 ultrasonic sensor nad plug it into an Arduino UNO board.

#define trigPin 9
#define echoPin 8
#define ledPin 13

long duration;
int distanceThreshold = 20; // Adjust this threshold according to your requirements

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

void loop() {
  // Trigger the ultrasonic sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echo duration
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance
  int distance = duration * 0.034 / 2;

  // Print distance to Serial Monitor (optional)
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Check if the object is within the specified range
  if (distance < distanceThreshold) {
    // Light up the LED (representing the bulb)
    digitalWrite(ledPin, HIGH);
  } else {
    // Turn off the LED if no object is detected or it's outside the range
    digitalWrite(ledPin, LOW);
  }

  // Delay before the next reading
  delay(500);
}

Here are the code I upload, but it it keep outputting 0 and 12 and 11.

13:46:55.487 -> Distance: 0 cm
13:46:55.990 -> Distance: 0 cm
13:46:56.474 -> Distance: 0 cm
13:46:56.978 -> Distance: 12 cm
13:46:57.486 -> Distance: 12 cm
13:46:57.954 -> Distance: 11 cm
13:46:58.501 -> Distance: 0 cm
13:46:59.005 -> Distance: 0 cm
13:46:59.501 -> Distance: 11 cm
13:46:59.978 -> Distance: 0 cm

Eventough it is facing the celling still it give output of 12 n 11 n 0.

anyone could help me :frowning: Thanks very much.

  • Confirm your yellow and brown pin connections on the Arduino.

  • The LED should have a 220 ohm series resistor connected to pin 13.

This may be a problem, as duration is also an integer. Not sure how the compiler is handling this. In just about all code I've seen distance is also a float. Try: int distance = float(duration) * 0.034 / 2;

Check whether your cables are not broken. Those cheap Chinese-made cables are highly unreliable, in my experience.

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