Ultrasonic Sensor – HC-SR04

Pictured above is the HC-SR04 ultrasonic ranging sensor. This provides 2cm to 400cm of non-contact measurement functionality  There are pins that you need to worry about on the HC-SR04: VCC (Power), Trig (Trigger), Echo (Receive), and GND (Ground).

For our first project with the HC-SR04 we will implement a simple range sensor with the Arduino Microprocessor.  You may use the male to female jumpers to connect directly to the Arduino or use a breadboard.  It may be easiest to plug the HC-SR04 into the breadboard to give it stability.

The pin labeled Vcc should be connected to the 5v power from the Arduino.  Gnd should be connected to the gnd pin on the Arduino.  Trig is connected to digital (PWM) pin 9 and Echo is connected to digital (pwm) pin 10.

Backside of SR-04 in breadboard








Top side view of HC-SR04 in breadboard









For our code, create a new sketch; compile and upload the following code:

*Kellenberg Computer Club
*Sonar Demonstration
// defines pins numbers
const int TriggerPin = 9;
const int EchoPin = 10;

// defines variables
long duration;
int distance;

int LoopCount=0;
int FirstTime=1;

/*This is the Setup Routine.  The Setup Routine will only execute one time per power cycle
 * or reset of the Arduion device
void setup() {
          /*First we configure our pins as INPUT and OUTPUT*/
          pinMode(TriggerPin, OUTPUT); // Sets the pin (9) as output.  It is sending a signal
          pinMode(EchoPin, INPUT); // Sets the pin (10) as Input.  Gets the signal
          /*Now we are opening the serial line so that we can
           * Send messages to the serial Monitor
          Serial.begin(9600); // We will us the serial port to monitor what is happening in the serial monitor
          /*Now we set the TriggerPin Low in initialize it*/
          digitalWrite(TriggerPin, LOW);

/*After setup is called, the loop function is called.  once loop gets to the bottom, starts over again.
void loop() {
          // Sets the TriggerPin on HIGH state for 10 micro seconds
          digitalWrite(TriggerPin, HIGH);
          digitalWrite(TriggerPin, LOW);
          // Reads the echoPin, returns the sound wave travel time in microseconds
          duration = pulseIn(EchoPin, HIGH);

          // Calculating the distance
          distance= duration*0.034/2;
          // Prints the distance on the Serial Monitor
          Serial.print("Distance: ");

Once your code is uploaded, open the serial monitor.  If you have a ruler set it alongside the breadboard and try measuring the distance between the SR-04 and a flat object, such as an iPad.

Here is a photo of a completed project.  Note the serial monitor is running in the background.  On the left is an iPad and to the right is the HC-SR04.

Below is a closer view of the serial monitor.

And a photo of the iPad sitting on a ruler to show the distance:

What other uses can you find for this sensor?