The HC-SR04 Ultrasonic Sensor is a versatile and cost-effective sensor that measures distance by emitting ultrasonic waves and detecting the time it takes for the echoes to return. It is widely used in robotics, obstacle avoidance systems, and range detection applications due to its non-contact measurement capability.
Pin Number | Pin Name | Description |
---|---|---|
1 | VCC | Power supply (5V DC) |
2 | Trig | Trigger input (TTL pulse) |
3 | Echo | Echo output (TTL level signal) |
4 | GND | Ground |
#include <Arduino.h>
// Define the Trig and Echo pin:
#define TRIG_PIN 9
#define ECHO_PIN 10
void setup() {
// Initialize serial communication:
Serial.begin(9600);
// Define the Trig pin as an output and the Echo pin as an input:
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Clear the Trig pin condition:
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Set the Trig pin HIGH for 10 microseconds:
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the Echo pin; pulseIn returns the duration (length of the pulse) in microseconds:
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance (in cm) based on the speed of sound (340 m/s):
long distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor:
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay for a half-second before the next measurement:
delay(500);
}
Q: Can the HC-SR04 sensor detect objects with soft surfaces? A: The sensor may have difficulty detecting soft or angled surfaces because they can absorb or deflect ultrasonic waves.
Q: What is the maximum range of the HC-SR04 sensor? A: The maximum range is approximately 4 meters, but optimal performance is usually within 2 meters.
Q: Can I use the HC-SR04 sensor with a 3.3V system? A: The HC-SR04 is designed for 5V systems. Using it with 3.3V may result in insufficient operation or damage to the sensor. Use a level shifter or a compatible sensor for 3.3V systems.
Note: The HC-SR04 Ultrasonic Sensor is not manufactured by Arduino UNO. The Arduino UNO is a microcontroller board used to interface with and control various electronic components, including the HC-SR04. The manufacturer part ID "Uno" refers to the Arduino UNO board, not the sensor itself.