int buzzer = 18;
int triggerPin = 5;
int echoPin = 17;
// Function to measure the time taken for ultrasonic waves to return
long readTime(int triggerPin, int echoPin) {
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
return pulseIn(echoPin, HIGH);
}
void initializeBuzzer() {
ledcSetup(0, 1000, 8); // LEDC channel, frequency, resolution
ledcAttachPin(buzzer, 0);
}
void setup() {
Serial.begin(9600);
// Set the buzzer pin as an output pin
pinMode(buzzer, OUTPUT);
// Initialize the buzzer
initializeBuzzer();
}
void loop() {
int distance;
// Calculate the distance using the readTime function
distance = 0.01715 * readTime(triggerPin, echoPin);
// Print the distance to the serial monitor
Serial.print("distance: ");
Serial.print(distance);
Serial.println("cm");
// Check the distance range and produce corresponding tones
if (distance > 50 && distance < 100) {
tone(buzzer, 1000); // Produce a tone of 1000Hz
} else if (distance < 50 && distance > 25) {
tone(buzzer, 3000); // Produce a tone of 3000Hz
} else if (distance < 25 && distance <= 100) {
tone(buzzer, 5000); // Produce a tone of 5000Hz
} else {
noTone(buzzer); // Turn off the buzzer if distance is above 100
}
delay(100); // Add a delay to make the output more readable
}