Introduction
Ultrasonic sensors work by emitting sound waves at a frequency too high for humans to hear. They then wait for the sound to be reflected back, calculating distance based on the time required. Since ultrasonic waves can reflect off a glass or liquid surface and return to the sensor head, even transparent targets can be detected.
Items Required
- Arduino Uno
- HC-SR04 Ultrasonic sensor
- Breadboard
- Jumpers
Circuit: Ultrasonic sensor
The HC-SR04 sensor has four pins, VCC, GND, Trig and Echo. Connect the VCC pin to the 5V pin of the board and the GND to the ground. After this, connect the Echo pin to D10 and the Trig pin to D9.
Sketch
First of all you need to define some variables for your project. No library is required to use the Ultrasonic sensor. In the setup() area, define the pin-mode and then begin the serial communication. Since we need to display the value which the sensor senses, so we print that in our serial monitor. The transmitter (trig pin) sends a signal: a high-frequency sound. When the signal finds an object, it is reflected and the transmitter (echo pin) receives it.
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup()
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
Here are some snaps from my actual project.