I'm trying to loop some code in the main function of the program, while running a thread in the background that's listening for a button press through GPIO. I can see that the thread is running, however the button presses aren't being registered. It works as two separate programs however doesn't seem to be working when combined.

    from threading import Thread
    import time
    import RPi.GPIO as GPIO


    GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_UP)
    GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)

    button1 = GPIO.input(23)
    button2 = GPIO.input(24)

    def buttonFunc():
        print("Button thread started.")

    while True:
        print("Button thread running...")

        if button1 == False:
            print("Button 1 pressed!!!")

        if button2 == False:
            print("Button 2 pressed!!!")

    Thread(target = buttonFunc).start()

    while True:
        print("Main program running.")
  • Is your ‘while true: print(‘button thread...’ supposed to be inside the buttonfunc? If so you need to indent that loop by 1 tab. – CoderMike May 5 at 10:56
  • This is a general programming question not belonging to Raspberry Pi. You should better ask at stackoverflow.com – Ingo May 6 at 11:22

Your Answer

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

Browse other questions tagged or ask your own question.