// Define the pins used for the ultrasonic sensor
const int trigPin = 4;
const int echoPin = 5;
// Define the pin used for the buzzer
const int buzzerPin = 12;
void setup() {
// Initialize the serial communication
Serial.begin(9600);
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the buzzer pin
pinMode(buzzerPin, OUTPUT);
tone(12, 262, 250);
}
void loop() {
// Trigger the ultrasonic sensor by sending a 10 microsecond pulse
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);
// Convert the duration to distance in centimeters
int distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If the distance is less than 30 centimeters, sound the buzzer
if (distance < 30) {
digitalWrite(buzzerPin, HIGH);
delay(1000);
digitalWrite(buzzerPin, LOW);
}
}