1

I am writing a code for Ultrasonic distance sensor. I have wired all the things perfectly and written the code for it but somehow it gives a runtime error of the channel already being in use. Below is my code:

import RPi.GPIO as gpio
import time

def distance(measure = 'cm'):
    gpio.setmode(gpio.BOARD)
    gpio.setup(12, gpio.OUT)   #Here it gives error of channel in use
    gpio.setup(16, gpio.IN)    

    gpio.output(12, False)     #it doesn't show me any value of distance
    while(gpio.input(16) == 0):
        nosig = time.time()

    while(gpio.input(16) == 1):
        sig = time.time()

    t = sig - nosig

    if(measure == 'cm'):
        distance = t / 0.000058
    elif(measure == 'in'):
        distance = t / 0.000148
    else:
        print('improper measurement: inches or centimeters')
        distance = None

    gpio.cleanup()
    return distance()

print(distance('cm'))
  • In future please post 'proper' code, without the pointed arrows at the start of the line. You probably copied this in IDLE. Much better to use a text editor / IDE instead of the IDLE interpreter. – Dirk Feb 6 at 15:54
1

That's because you're running gpio.setup() on that pin every time you call that function. You need to run setmode and setup once, and then just check the distance in the function.

gpio.setmode(gpio.BOARD)
gpio.setup(12, gpio.OUT)   #Here it gives error of channel in use
gpio.setup(16, gpio.IN) 

def distance(measure = 'cm'):
    gpio.output(12, False)
    ...

You might find it easier to use gpiozero's DistanceSensor class instead.

  • No, the program should run atleast once but, when i run it it executes but doesn't show any values of distance. I don't know whether it's because of GPIO pin issue or something else but, the sensor doesn't seem to be receiving the input somehow. – Muhammad Hassan Feb 6 at 15:02
  • @MuhammadHassan - well, you still need to move the setup code outside the function def, so that it will only be run once. As Ben says: the error you get is a result of the repeated init calls. Debugging can continue after you corrected that. – Dirk Feb 6 at 15:58

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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