Ultrasonic sensor
The Ultrasonic Sensor is a device that uses sound waves to detect the distance of an object. It consists of a transmitter and a receiver. When the sensor is triggered, the transmitter emits high-frequency sound waves that bounce off objects in its path and return to the receiver. The receiver converts them into electrical signals that are processed by the sensor's control circuitry. The time taken for the sound wave to return is used to calculate the distance between the sensor and the object.
These sensors are commonly used in robotics, automation, security systems, and various applications, such as parking sensors, obstacle detection, and distance measurement. It is easy to use and can be connected to a microcontroller using only four pins. They are known for their accuracy, reliability, and ease of use, making them a popular choice for many different industries.
In this project, we will measure the distance of an obstacle in front of the sensor.
#define TRIG_PIN 23 //GPIO23 connected to Sensor's TRIG pin
#define ECHO_PIN 22 //GPIO22 connected to Sensor's ECHO pin
float duration_us, distance_cm, distance_inch;
void setup() {
Serial.begin (9600); //begin serial port
pinMode(TRIG_PIN, OUTPUT);//configure the trigger pin to output mode
pinMode(ECHO_PIN, INPUT); //configure the echo pin to input mode
}
void loop() {
//generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
//measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
//calculate the distance (Check below for more explanation)
distance_cm = (duration_us / 29) / 2;
distance_inch = 0.393701 * distance_cm;
//print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.print(" cm");
Serial.print(" or ");
Serial.print(distance_inch);
Serial.println(" in");
delay(500);
}