I have used python for a while now, however, I am new to using a Raspberry Pi and things such as GPIO pins. I recently bought a Freenove Ultrasonic starter kit to help me learn. They have a tutorial included that I am following. In the program I keep getting this error message:
lgpio.error 'gpio busy'
I have tried loads of things. I know it could be a few things: In a previous project I didn't cleanup the GPIO pins properly or I exported the pins and didn't reverse it.
I have tried numerous commands and script to cleanup the code but it wont work. I also rebooted the Raspberry Pi5 a few times. Here is the code I used for my project:
from gpiozero import LED, Button
import time
led = LED(17) # define LED pin according to BCM Numbering
button = Button(18) # define Button pin according to BCM Numbering
def onButtonPressed():
# When button is pressed, this function will be executed
led.toggle()
if led.is_lit:
print("Led turned on >>>")
else:
print("Led turned off <<<")
def loop():
# Button detect
button.when_pressed = onButtonPressed
while True:
time.sleep(1)
def destroy():
led.close()
button.close()
if __name__ == '__main__':
# Program entrance
print('Program is starting...')
try:
loop()
except KeyboardInterrupt:
# Press ctrl-c to end the program.
destroy()
print("Ending program")
The Error is in your "loop" function. First of all you are assigning your "onButtonPressed" function to the class function "when_pressed" of Button, which you have assigned your button variable to. Then you put "sleep(1)" in a loop which pauses the main thread you are trying to execute your program on.
The correct approach to listening to your button input would be something like this:
def loop():
while True:
if(button.when_pressed):
onButtonPressed()
time.sleep(1)
Note: because of missing context here I am assuming that "button.when_pressed" returns something like "True" or "False".