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
- 16
- 2