Other Arduino Codes and Videos by Robojax

Arduino code and video for HC-SR04 Ultrasonic Distance Sensor

دروس آردوینو به فارسی

This is the Arduino code for HC-SR04 Ultrasonic Distance Sensor

This video shows you how to use HC-SR04 Ultrasonic Distance Sensor for arduino. http://robojax.com/learn/arduino/
  1. HC-SR04 Ultrasonic Library (from Robojax.com)
  2. HC-SR04 Ultrasonic Library from Arduino official website

 * This is the Arduino code for  HC-SR04 Ultrasonic Distance Sensor
 * to measure the distance using arduino for robotoic car and other applications
 * Watch the video https://youtu.be/QI9541YQq7M
 *  * 
 * Written by Ahmad Shamshiri for Robojax Video
 * Date: Dec 21, 2017, in Ajax, Ontario, Canada
 * Permission granted to share this code given that this
 * note is kept with the code.
 * Disclaimer: this code is "AS IS" and for educational purpose only.

/* Original Code 
// https://playground.arduino.cc/Code/NewPing
 * Modified for Robojax video on Dec 21, 2017


// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#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(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  int distance = sonar.ping_cm();// store the distance value in "distance" variable
  if(distance <=12){             // if distance is less than 12, do somethings. For example here just print "very close"
    Serial.println("Very close");

If you found this tutorial helpful, please support me so I can continue creating content like this. support me via PayPal