Arduino - Ultrasonic Sensor
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module.
Components required
- Breadboard x 1 (optional)
- Arduino Uno R3 x 1
- Ultrasonic Sensor (HC-SR04) x 1
- Jumper x 4 (Female-Male)
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Ultrasonic Sensor 5V - Arduino VCC
Ultrasonic Sensor GND - Arduino GND
Ultrasonic Sensor Trigger Pin - Arduino Pin 7
Ultrasonic Sensor Echo Pin - Arduino Pin 6
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the new sketch File by clicking New and save it by pressing Ctrl + Shift + S.
Arduino Code
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor const int echoPin = 6; // Echo Pin of Ultrasonic Sensor void setup() { Serial.begin(9600); // Starting Serial Terminal } void loop() { long duration, inches, cm; pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(10); digitalWrite(pingPin, LOW); pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; }
download the code by using this link
Code to Note
- Connect the 5V pin to 5V on your Arduino board.
- Connect Trigger to digital pin 7 on your Arduino board.
- Connect Echo to digital pin 6 on your Arduino board.
- Connect GND with GND on Arduino.
In our program, we have displayed the distance measured by the sensor in inches and cm via the serial monitor.
Nice
ReplyDelete