Loading... Please wait...

HC-SR04 Ultrasonic Distance Sensor

HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 is an ultrasonic distance sensor. It detects the distance of the closest object in front of the sensor (from 2 cm up to 3m). It works by sending out a burst of ultrasound and listening for the echo when it bounces off of an object. The Arduino board sends a short pulse to trigger the detection, then listens for a pulse on the echo pin. The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.

Hardware Required

  • Arduino Board
  • (1) HC-SR04 Ultrasonic Distance Sensor
  • Jumper wire

Circuit

The 5V pin of the HC-SR04 is connected to the 5V pin on the Arduino, the GND pin is connected to the GND pin,  the TRIG (trigger pin is connected to digital pin 8 and the ECHO is connected to pin 9 on the Arduino.

 

hcsr04-2.png

Image developed using Fritzing. For more circuit examples, see the Fritzing project page

Code

Download the NewPing library here.

 

#include 

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(115200);
}

void loop() {
  delay(50);
  int uS = sonar.ping();
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM);
  Serial.println("cm");
}

 

 

What's News

newsletter

Copyright 2019 oddWires. All Rights Reserved.
 Sitemap | oddWires