Why does my HCR04 u...
 
Notifications
Clear all

Why does my HCR04 ultrasonic sensor give randome readings?

1 Posts
2 Users
0 Reactions
2,092 Views
0
Topic starter

I'm using an HC-SR04 ultrasonic sensor with my Arduino to measure distance, but I'm getting inconsistent readings. Sometimes it works fine, but other times the values jump around randomly, even when there's no object moving.

Here's my code:

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

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);

    long duration = pulseIn(echoPin, HIGH);
    int distance = duration * 0.034 / 2;

    Serial.println(distance);
    delay(500);
}

The issues I am facing:

  • The sensor sometimes returns very high or very low values randomly.
  • The readings are unstable even when there’s a fixed object in front of it.
  • Sometimes I even get 0 cm, even though there’s no obstacle that close.

 


1 Answer
0

Before checking the sensor deeply, you should first check the power supply, as the sensor is sensitive to power supply stability. If you're powering it from an unstable source (like USB power or a breadboard with poor connections), voltage fluctuations can cause erratic readings. 

To reduce power instability:

      1. Place a 100µF capacitor (electrolytic) directly across the VCC and GND pins of the HC-SR04 sensor.

      2. This capacitor acts like a small energy reservoir, providing extra current during those brief spikes in demand, thus smoothing out voltage dips.


Share: