int trigPin = 6;
int echoPin = 5;
void setup() {
pinMode(8, OUTPUT); // Pin for buzzer
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
delay(1000);
}
void loop() {
// Send a pulse to the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Send a 10-microsecond pulse
digitalWrite(trigPin, LOW);
// Measure the pulse duration on the echo pin
int duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
long distance = duration * 0.0344 / 2;
// Print the distance to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Map the distance (20cm to 200cm) to a frequency (2000Hz to 4000Hz)
long frequency = map(distance, 20, 200, 2000, 4000);
// Make sure the frequency is within the audible range (2000Hz - 4000Hz)
frequency = constrain(frequency, 2000, 4000);
// Play tone based on mapped frequency
tone(8, frequency, 2000); // Play the tone for 2 seconds
delay(2500); // Wait for the tone to finish before the next reading
// Stop the tone after it finishes
noTone(8);
}