I have built a simple robot car with an ultrasonic sensor.

However I wanted 2 more since it can't detect distance when it's driving not straight to a wall. So I added 2 more, but it seems like only one of them are reading distance (and it's not the first one)

import RPi.GPIO as GPIO
import time

    while True:

          PIN_TRIGGER = 7
          ECHOS = [11, 13, 15]
          for e in ECHOS:
              GPIO.setup(e, GPIO.IN)

          GPIO.setup(PIN_TRIGGER, GPIO.OUT)

          GPIO.output(PIN_TRIGGER, GPIO.LOW)

          print ("Waiting for sensor to settle")


          print ("Calculating distance")

          GPIO.output(PIN_TRIGGER, GPIO.HIGH)


          GPIO.output(PIN_TRIGGER, GPIO.LOW)

          while GPIO.input(e) == 0:
                pulse_start_time = time.time()
          while GPIO.input(e) == 1:
                pulse_end_time = time.time()

          pulse_duration = pulse_end_time - pulse_start_time
          distance = round(pulse_duration * 17150, 2)
          if distance < 30:
              print("Object close")
          #print ("Distance:",distance,"cm")


All 3 are working if I change the for loop to one of the ECHO numbers (11, 13, 15)

2 Answers 2


You seem to be trying to read each sensor at the same time. That will not work (did the echo come from the sending sensor or another one).

You need to fire each sensor in succession.

I.e. rather than

trigger A, B, C
get echo A, B, C
calculate distance A, B, C


trigger A
get echo A
Calculate distance A

trigger B
get echo B
Calculate distance B

trigger C
get echo C
Calculate distance C

This is pseudo code for what I mean.

echo=[5, 11, 10] # example GPIO for echo lines
trigger=[7, 8, 23] # example GPIO for trigger

for i in range(len(echo)): # for each sensor
   send trigger[i]
   time echo[i]
   calculate distance for sensor i
  • Ok Thanks for the quick answer, I thought That I could use a for loop. Thanks for the help
    – Kungbjucha
    Commented May 19, 2019 at 15:29
  • @Kungbjucha Yes, do use a for loop, but use different trigger and echo GPIO for each sensor. Also as you need to power the sensors from 5V make sure you have a voltage divider to 3V3 on the echo GPIO.
    – joan
    Commented May 19, 2019 at 15:32
  • If I understand correctly I shall keep the for loop but add triggers for all sensors ?(they share the same now)
    – Kungbjucha
    Commented May 19, 2019 at 17:26

I got it to work now, however I could not get it to work with the for loops so instead I have 3 functions one for each sensor that are all in a While True loop and when one of them detects something it will report it I probably would have looked nicer code wise with for loops so Im gonna see if I can get it to work

Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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