0

trying print values for two sensors, one works the other is 0, any tips on how i can use more than one?

const int pingPin = 10;
const int pingPinz = 11;
unsigned int duration1, duration2, inches1, inches2;

void setup() {
  Serial.begin(9600);
}

void loop() {
  pinMode(pingPin, OUTPUT);          // Set pin to OUTPUT
  pinMode(pingPinz, OUTPUT);          // Set pin to OUTPUT
  digitalWrite(pingPin, LOW);        // Ensure pin is low
  digitalWrite(pingPinz, LOW);        // Ensure pin is low
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);       // Start ranging
  digitalWrite(pingPinz, HIGH);       // Start ranging
  delayMicroseconds(5);              //   with 5 microsecond burst
  digitalWrite(pingPin, LOW);        // End ranging
  digitalWrite(pingPinz, LOW);        // End ranging
  pinMode(pingPin, INPUT);           // Set pin to INPUT
  pinMode(pingPinz, INPUT);           // Set pin to INPUT
  duration1 = pulseIn(pingPin, HIGH); // Read echo pulse
  duration2 = pulseIn(pingPinz, HIGH); // Read echo pulse
  inches1 = duration1 / 74 ;        // Convert to inches
  inches2 = duration2 / 74 ;        // Convert to inches
  Serial.println(inches1);            // Display result
  Serial.println(inches2);            // Display result
  delay(200);                 // Short delay
}
1

Your problem is in how you are working with the two sensors. At the moment you are triggering both sensors together then waiting for the first one to echo back. Only when that has responded do you then wait for the second one to echo back, and that echo has been and gone already.

Imagine you have two tennis balls. You throw them both at different walls at the same time, then attempt to catch them both. While you are catching the first ball the second one bounces off the back of your head and rolls under the table. That's what's happening with your echos.

So instead you need to treat both sensors completely separately. Trigger the first, then get the response. Then trigger the second and get the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.