I am trying to make a radar with to ultrasonic sensors that are at a 30ish degree angle away from each other. If on detects an object, they will turn to try ad face the object. The issue im facing is that one of the sensors always returns 0 when i call the pulsein command. I am certain that both sensors are not broken and that the wiring is fine. I am sure that the issue is not interference since i am running the sensos individually with a half second delay between each use. Any suggestions on how i can get it to work?
Heres the code:
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;
}