This tutorial is about how to use Ultrasonic Sensor HC-SR04 with Arduino UNO, The Ultrasonic HC-SR04 sensor uses SONAR to determine the distance to an obstacle or an object like Bats, an excellent digital non-contact range detection with high accuracy and stable reading. From 2 centimeter to 400 centimeter. The operation is not affected by any light or a colored objects it has a sharp rangefinder although acoustically soft material like cloth can be difficult to detect. it has a complete sonar powered Ultrasonic Transmitter and Receiver Module, Tested in Arduino, Raspberry Pi and Common Micro Controller.
Features
• Power Supply :+5V DC
• Quiescent Current : <2mA
• Working Current: 15mA
• Effectual Angle: <15°
• Measuring Angle: 30 degree
• Trigger Input Pulse width: 10uS
• Dimension: 45mm x 20mm x 15mm
• Ranging Distance : 2cm – 400 cm/1″ – 13ft
• Resolution : 0.3 cm
Connecting to Arduino Board
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
int trigPin = 10; //Trig int echoPin = 11; //Echo long duration, cm, inches; void setup() { Serial.begin (9600); //Serial Port begin pinMode(trigPin, OUTPUT); //Define outputs pinMode(echoPin, INPUT); //Define inputs } void loop() { // The sensor will going to triggered by a HIGH pulse of 10 or more microseconds. // Provide a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor a HIGH pulse // The duration time in microseconds from the broadcast // of the ping to the reception of its echo off of an obstacle. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // converting the time into a distance cm = (duration/2) / 29.1; inches = (duration/2) / 74; Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(250); } |
Using the Arduino Libary New Ping
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* * Posted on http://randomnerdtutorials.com * created by http://playground.arduino.cc/Code/NewPing */ #include <NewPing.h> #define TRIGGER_PIN 12 #define ECHO_PIN 11 #define MAX_DISTANCE 200 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void setup() { Serial.begin(9600); } void loop() { delay(50); unsigned int uS = sonar.ping_cm(); Serial.print(uS); Serial.println(“cm”); } |