#define TRIGGER_PIN_1 2
#define ECHO_PIN_1 3
#define BUZZER_PIN_1 7
/* #define TRIGGER_PIN_2 5
#define ECHO_PIN_2 4
#define BUZZER_PIN_2 6 */
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN_1, OUTPUT);
pinMode(ECHO_PIN_1, INPUT);
pinMode(BUZZER_PIN_1, OUTPUT);
/* pinMode(TRIGGER_PIN_2, OUTPUT);
pinMode(ECHO_PIN_2, INPUT);
pinMode(BUZZER_PIN_2, OUTPUT); */
}
void measureDistance(int triggerPin, int echoPin, int buzzerPin) {
long duration, distance;
// Send a pulse to the ultrasonic sensor to start measurement
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Measure the time it takes for the pulse to return
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = (duration * 0.0343) / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object is within a certain range (adjust as needed)
if (distance < 30) {
// If an object is detected, activate the buzzer
tone(buzzerPin, 1000); // You can adjust the frequency as needed
} else {
// If no object is detected or it's out of range, turn off the buzzer
noTone(buzzerPin);
}
}
void loop() {
measureDistance(TRIGGER_PIN_1, ECHO_PIN_1, BUZZER_PIN_1);
delay(100); // Add a small delay between sensor readings
/* measureDistance(TRIGGER_PIN_2, ECHO_PIN_2, BUZZER_PIN_2);
delay(1000); // Adjust the delay as needed for your application */
}