0

I am using a HC-SR04 ultrasonic sensor to measure the distance using an Arduino Uno. When I run this code which is worked perfectly in the previous, it only shows just random readings in the serial monitor. the sensor is little old and there is good chance for it to be damaged. So I want to know is it a problem in my code or could it be a problem in the sensor?

#define trig 2
 #define echo 4

void setup() { pinMode(trig,OUTPUT); pinMode(echo,INPUT); Serial.begin(9600);

}

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

long t = pulseIn(echo,HIGH);

long inches = t/74/2; long cm = t/29/2; Serial.print(inches); Serial.print("inch \t"); Serial.print(cm); Serial.println("cm"); delay(500);

}

Y_Jay
  • 3
  • 2

1 Answers1

0

Your code is fine. The problem is very likely a bad HC-SR04 module, loose wiring, or unstable power supply. These sensors can degrade, especially if exposed to moisture or dust. Internal transmitter/receiver or timing IC can fail, causing noise or stuck readings.HC-SR04 requires 5V (not 3.3V). If powered from unstable source (like weak USB port), the sensor may give noisy results.Try powering from Arduino 5V pin directly.

Replace with another HC-SR04.

Or use a simple LED test. connect the echo pin to an LED+resistor. Trigger the sensor and see if the LED flickers — if not, the sensor isn’t producing an echo pulse.

Try a known-good library like NewPing (https://docs.arduino.cc/libraries/newping/). If still random hardware problem.

These projects may give you some more insights.

https://projecthub.arduino.cc/Isaac100/getting-started-with-the-hc-sr04-ultrasonic-sensor-7cabe1

https://www.pcbway.com/project/shareproject/DIY_Advanced_Theremino_Sonar_f4408c86.html