I'm trying to fix this code for a robot with multiple sensors. The values of TRIG and ECHO are input through another part of the code.

Set this at the beginning of the code

def init():

This is the function where I'm getting the error

def getSensor(TRIG,ECHO):
        #Set the pins for TRIG, trig is the output pin 
        GPIO.setup(TRIG,GPIO.OUT) #Error right here
        #Set the pins for ECHO, echo is the input pin
        #3.3v sent to trig
        #turn off the trig pin
        while GPIO.input(ECHO) == 0:
        start = time.time()
        while GPIO.input(ECHO) == 1:
        stop = time.time()
        reading = (stop - start) * 17000
        return reading    
    except KeyboardInterrupt:
        print ("Interrupted by keyboard")
        print ("Other error or exception occured")

How can I fix this? I can't figure out where I'm going wrong

  • Related if not dupe: raspberrypi.stackexchange.com/q/55143/19949 – Ghanima Jul 22 '19 at 21:11
  • Have you looked at the warning message? It used to tell you exactly what you needed to do to stop the warning. – joan Jul 22 '19 at 21:18
  • @Ghanima I read through that right before posting this, i believe the error is the same, but can't figure out what exactly i should change – Shreesh Jul 22 '19 at 21:22
  • @joan it says to use GPIO.setwarnings(False) to disable it, but that just ignores the error, and doesn't help me use the robot – Shreesh Jul 22 '19 at 21:23
  • Warnings are just warnings, not errors. And you can turn them off. – ben_nuttall Jul 22 '19 at 21:42

Debugging without all relevant code is a hit and miss affair.

Your problem is most likely to be caused by calling GPIO.setup() inside a function. This should be called ONCE in your program.

Calling GPIO.setmode multiple times is also an error it definitely should be called ONCE only.

NOTE there is actually nothing wrong with calling the setup multiple times, but Python is quite correctly warning you.

  • Thanks for this clarification! It helped! – Shreesh Jul 24 '19 at 0:00

I'm guessing you don't see this every time, but maybe every 2nd run? Here's why: When you run it the first time, your code exits the function through the 'return reading' statement, skipping the gpio.cleanup() line. This leaves the pins in an 'in use' state.

When is gets called again or you run it a second time, your call to gpio.setup() triggers an exception, but then in your finally clause you call gpio.cleanup() which frees up the pins. If you run it again, it'll work starting the cycle over.

The solution is to simply add a gpio.cleanup() before the return statement

  • return reading exits the function NOT the program (we don't actually know what is in the program) – Milliways Jul 24 '19 at 0:04
  • Thanks Miliways. I edited my answer. – tbitson Jul 24 '19 at 21:51

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