My While True loop is getting stuck in python

2.4k views Asked by At

Hello I have been working on an infinite While True loop for the main file in my python code. I am working on a Raspberry Pi and my goal is that whenever one of the GPIO Pins senses an input it will print out a string. However When I push a button it will keep printing it infinitely and the only way for it to stop is by hitting Ctrl-C. While it is printing the same string over and over no other button will change what happens. What am I doing wrong did I forget a step somewhere?

import RPi.GPIO as GPIO
import time
from time import sleep
GPIO.setmode(GPIO.BCM)

GPIO.setup(26, GPIO.IN)
GPIO.setup(19, GPIO.IN)
GPIO.setup(13, GPIO.IN)
GPIO.setup(6, GPIO.IN)

input_A = GPIO.input(26)
input_B = GPIO.input(19)
input_C = GPIO.input(13)
input_D = GPIO.input(6)

while True:
    if input_A == True:
            print('A was pushed')

    if input_B == True:
            print('B was pushed')

    if input_C == True:
            print('C was pushed')

    if input_D == True:
            print('D was pushed')

    sleep(1.5);
4

There are 4 answers

0
Peter Gibson On BEST ANSWER

You need to keep updating your input_* variables inside your while loop

while True:
    input_A = GPIO.input(26)
    input_B = GPIO.input(19)
    input_C = GPIO.input(13)
    input_D = GPIO.input(6)

    if input_A == True:
            print('A was pushed')

    if input_B == True:
            print('B was pushed')

    if input_C == True:
            print('C was pushed')

    if input_D == True:
            print('D was pushed')

    sleep(1.5);
1
AudioBubble On

At the break statement under each if-statement. While you're at it, change the 2nd to last ifs to elifs.

while True:
    if input_A == True:
        print('A was pushed')
        break
    elif input_B == True:
        print('B was pushed')
        break
    elif input_C == True:
        print('C was pushed')
        break
    elif input_D == True:
        print('D was pushed')
        break
0
tomasyany On

When you declare

input_A = GPIO.input(26)
input_B = GPIO.input(19)
input_C = GPIO.input(13)
input_D = GPIO.input(6)

you are assigning a value to those variables that will not change, because you are not updating them inside the loop.

Therefore, you need to add a line in the loop that updates the inputs A B C and D.

0
pycod333 On

why don't you try introducing a break for each if statement. It should stop it from looping infinitely.

and updating your variables i.e the inputs should be in the while loop.

e.g

if input_A == True:
    print('A was pushed')
    break