Introduction :
The HC-SR04 is an affordable and popular ultrasonic distance sensor widely used in robotics and various automation projects. It measures the distance to an object by using ultrasonic sound waves
Key Features
- Operating Voltage: 5V DC
- Quiescent Current: <2mA
- Operating Current: 15mA
- Measuring Range: 2 cm to 400 cm
- Resolution: 0.3 cm
- Frequency: 40 kHz
- Dimensions: 45mm x 20mm x 15mm
Pin Configuration
- VCC: Power supply (5V)
- Trig: Trigger input
- Echo: Echo output
- GND: Ground
Code :
const int trigPin = 9; // Trigger pin
const int echoPin = 10; // Echo pin
long duration;
float distanceCm;
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud
pinMode(trigPin, OUTPUT); // Set the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Set the echoPin as an INPUT
}
void loop() {
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print(“Distance: “);
Serial.print(distanceCm);
Serial.println(” cm”);
delay(1000); // Wait for 1 second before taking the next measurement
}
https://github.com/makertribe/IoT-Codes/blob/2a7e8645891fba590b21c8a1b9db02ee2c0192ae/Ultrasoundsensor
Output :