Home Sensor Projects HC-SR04 Ultrasonic Sensor example

HC-SR04 Ultrasonic Sensor example

by shedboy71

The HC-SR04 Ultrasonic Sensor uses sonar to determine distance to an object like bats or dolphins do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package. From 2cm to 400 cm or 1” to 13 feet. It operation is not affected by sunlight or black material like Sharp rangefinders are (although acoustically soft materials like cloth can be difficult to detect). It comes complete with ultrasonic transmitter and receiver module.

 

Features:

  • Power Supply :+5V DC
  • Quiescent Current : <2mA
  • Working Currnt: 15mA
  • Effectual Angle: <15°
  • Ranging Distance : 2cm – 400 cm/1″ – 13ft
  • Resolution : 0.3 cm
  • Measuring Angle: 30 degree
  • Trigger Input Pulse width: 10uS
  • Dimension: 45mm x 20mm x 15mm

Here is a picture of the sensor

HC-SR04 Ultrasonic Sensor

HC-SR04 Ultrasonic Sensor

Again connections are not difficult, Vcc goes to 5v, Gnd goes to Gnd

Trig is connected to pin 8 in our example
Echo is connected to pin 7 in our example

Code

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
 
long duration, distance; // Duration used to calculate distance
 
void setup()
{
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
 
void loop()
{
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
Serial.println(distance);
//Delay 50ms before next reading.
delay(50);
}

 

Links

A low cost sensor that I recommend you add to your parts collection, you can easily pick these up for $2 to $3 a piece

HC-SR04 Ultrasonic Module Wave Sensor Ranging Detector Distance Module for Arduino

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More