Safari browser sometimes has issues displaying images...

I.e: *you have to click on the images to see them...

For a better browsing experience on Brainy-Bits

Please use Chrome, Edge or Firefox browser.

  • Brainy-Bits

Using the HC-SR04 Ultrasonic Range Sensor with an Arduino



OVERVIEW


Ultrasonic sensor are great for all kind of projects that need distance measurements, avoiding obstacles as examples.


The HC-SR04 are inexpensive and easy to use since we will be using a Library specifically designed for these sensor.


PARTS USED

HC-SR04 Ultrasonic sensor

Amazon usa

Amazon canada


Arduino UNO

Amazon usa

Amazon canada


Dupont Wires

Amazon usa

Amazon canada


These are Amazon affiliate links...

They don't cost you anything and it helps me keep the lights on

if you buy something on Amazon. Thank you!

CONNECTIONS




As you can see, we only need 4 connections :  Voltage, Ground, Trigger and Echo.


THE CODE


Using a Library designed for these sensors will make our code short and simple.


We include the library at the beginning of our code, and then by using simple commands we can control the behaviour of the sensor.

Once you have the library, just go ahead and extract it to the Library folder inside your Arduino IDE software folder.  


Make sure to restart the IDE software so the library is loaded at startup.


#include "NewPing.h"

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(500);  // Wait 500ms between pings (about 2 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
  Serial.println("cm");
}


TUTORIAL VIDEO




DOWNLOAD


Copy and Paste the above Sketch/Code in your Arduino IDE.


You can download the NewPing Library we used here: NewPing-Library

19 views

All my content is and will always be Free.

If you feel that my Videos / Tutorials are helping, and you would like to contribute...

 You can toss some coins in the Tip Jar via PayPal.

Select amount then click the “Donate” button.

©2020 by Brainy-Bits