May 15, 2021 Arduino
The HC-SR04 ultrasonic sensor uses sonar to determine the distance of an object, just like a bat. It offers excellent non-contact range detection, high accuracy, stable readings and ease of use, ranging in size from 2 cm to 400 cm or 1 inch to 13 feet.
Its operation is not affected by sunlight or black materials, although acoustically soft materials such as cloth may be difficult to detect. It is equipped with an ultrasonic transmitter and receiver module.
You will need the following components:
Connect according to the circuit diagram, as shown in the following image.
Turn on the Arduino IDE software on your computer. U se arduino to encode and control your circuitry. Open a new sketch file by clicking New.
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; }
The ultrasonic sensor has four terminals: : 5V, Trigger, Echo and GGND, connected as follows:
In our program, we show the distance measured by the sensor in inches and centimeters through the serial port.
You will see the distance measured by the sensor in inches and centimeters on the Arduino serial monitor.