Ultrasonic Sensor
Here is some information about the HC-SR04 ultrasonic sensor, which can be used to determine the distance between an object and the sensor. The sensor is made up of an ultrasonic emitter and receiver. By measuring the time it takes for sound to travel from the emitter to the object and back to the receiver, the sensor can determine the distance. This article includes wiring diagrams, code examples, pinouts, and technical data to help you use the sensor effectively.
The HC-SR04 ultrasonic sensor has four pins: Vcc+, Trigger, Echo, and Ground
The ultrasonic sensor has both an emitter and a transmitter that work at a frequency of 40kHz, which is beyond the hearing range of humans and most animals.
Tech Specs for the HC-SR04 Ultrasonic Sensor:
const int echoPin = 9;
const int triggerPin = 10;
// defines variables
long timetofly;
int distance;
void setup() {
pinMode(triggerPin, OUTPUT); // Sets trigger to Output
pinMode(echoPin, INPUT); // Set echo to Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the triggerPin
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the triggerPin on HIGH state for 10 micro seconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Reads the echoPin, returns the travel time in microseconds
timetofly= pulseIn(echoPin, HIGH);
// Calculating the distance (Time to Fly Calculation)
distance= timetofly*0.034/2;
// Prints the distance on the Serial Monitor in CM
Serial.print(" Distance: ");
Serial.println(distance);
}