Ultrasonic distance measuring
Components:
1-ِArduino
2- Ultrasonic sensor
3-Buzzer
4- wires
Connections:
pin : pin
pin : pin
pin : pin
Code:
// Define the ultrasonic sensor pins
#define trigPin 2
#define echoPin 3
// Define the buzzer pin
#define buzzerPin 4
void setup() {
// Set the ultrasonic sensor pins as input/output
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set the buzzer pin as output
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Send a pulse to the ultrasonic sensor to start a distance measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the ultrasonic sensor
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
int distance = duration / 58;
// Check if the distance is less than 50 centimeters (half a meter)
if (distance < 50) {
// Turn on the buzzer
digitalWrite(buzzerPin, HIGH);
} else {
// Turn off the buzzer
digitalWrite(buzzerPin, LOW);
}
// Wait for a short period oftime before taking another measurement
delay(100);
}
OK tamam