Proje Defteri

HC-SR04 Code Generator

Generate ready Arduino code for the HC-SR04 ultrasonic distance sensor in seconds. Pick the pins, unit and method, then copy the code.

What is the HC-SR04 Ultrasonic Distance Sensor?

The HC-SR04 is a cheap, popular ultrasonic sensor that measures distance with sound waves. It sends a sound pulse, measures how long the pulse takes to bounce off an object and return, and calculates distance from that time. It is widely used in Arduino projects for parking sensors, robot obstacle avoidance and level measurement. This tool builds ready-to-flash code from your chosen pins, unit and method.

Wiring (Arduino Uno)

Distance Formula

The speed of sound is about 0.0343 cm/µs. Because the echo travels there and back, the total time is divided by 2: distance = time × 0.0343 / 2 (cm). For inches, roughly 0.0135 is used instead of 0.0343.

Frequently Asked Questions

Can I change the Trig and Echo pins?

Yes. You can use any two digital pins; the values you enter above are reflected in the code automatically.

Should I use NewPing or pulseIn?

Library-free pulseIn is enough for a quick start. For multiple sensors or more stable readings, use the NewPing library (install it from the Library Manager).

My readings are always 0 or very large.

Check the Trig/Echo wiring and the 5V supply. Leave at least a few centimeters of clearance in front of the sensor; very close or very soft surfaces can cause bad readings.