Connecting the HC-04 Ultrasonic Sensor To The Arduino Robot

How The Sensor Works:

Connecting an ultrasonic sensor to the Arduino lets you detect obstacles and measure distances. The sensor has a working range of 2cm-450cm.

The pinout of the ultrasonic sensor is as follows:

Vcc, Trig, Echo and GND.

As with all of our sensors, Vcc gets connected to the positive power rail on your breadboard and GND gets connected to the negative power rail.

The Trig and Echo pins are unique to this type of sensor so they need to be explained a bit.


Source :

The Trig pin on the sensor is an input. It waits for a signal from the Arduino (a trigger) to send out an ultrasonic ping. The way it works is the Trig pin waits for a short pulse. All the Arduino has to do is make the trig pin HIGH for a few microseconds and then LOW again and the trigger will be activated.

The Echo pin is the output from the sensor and it what tells us how far away things are.  The split second the ultrasonic ping gets sent out, the ECHO pin goes high. As soon as the ultrasonic pulse bounces off something and arrives back at the sensor the ECHO pin goes low again. In this way we can measure how long it too for the ultrasonic ping to leave the sensor and return by looking the the ECHO pin.


Wiring The Sensor:

Any of the GPIO pins on the Arduino can be used for the TRIG and ECHO pins but to match up with the example code below, use pins 6 and 7 as shown in this diagram:

Wiring Diagram for HC-SR04 Sensor


Example Code 1 – Plotting Sensor Values:

Now that we have the sensor wired, take a look at the example code below which will trigger the sensor, time the pulse, use the formula shown above, and print the results out via the serial port.

Once this is uploaded and running, open up the Arduino serial monitor to take a look at the values getting returned. The Serial plotter is also useful as you can move your hand in front of the sensor and see the graph going up and down.


Example Code 2 – Blinking LEDs based on sensor value:

This code increases the blink rate of the green and red LEDs based on the ultrasonic sensor value. The lower the distance value, the faster the LEDs blink.




This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *