const int trigPinA = 12; // Trigger pin for Sensor A
const int echoPinA = 11; // Echo pin for Sensor A
const int trigPinB = 9; // Trigger pin for Sensor B
const int echoPinB = 10; // Echo pin for Sensor B
void setup() {
Serial.begin(9600);
Serial.println("Ultrasonic Sensors Initialized!");
pinMode(trigPinA, OUTPUT);
pinMode(echoPinA, INPUT);
pinMode(trigPinB, OUTPUT);
pinMode(echoPinB, INPUT);
}
void loop() {
// Measure and print distance for Sensor A
float distanceA = measureDistance(trigPinA, echoPinA);
Serial.print("Distance A: ");
Serial.println(distanceA >= 0 ? String(distanceA) + " cm" : "Error");
// Short delay to avoid interference
delay(500);
// Measure and print distance for Sensor B
float distanceB = measureDistance(trigPinB, echoPinB);
Serial.print("Distance B: ");
Serial.println(distanceB >= 0 ? String(distanceB) + " cm" : "Error");
// Wait before repeating
delay(500);
}
float measureDistance(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000); // 30 ms timeout
if (duration == 0) return -1; // No valid pulse received
float distance = (duration / 2.0) * 0.0343; // Calculate distance in cm
return distance;
}