Sign up ×
Raspberry Pi Stack Exchange is a question and answer site for users and developers of hardware and software for Raspberry Pi. It's 100% free, no registration required.

I am writing a program in python on RaspberryPi, to stop While loop through GPIO input.

I don't know why it is not working.

Can you please look on my coding and guide me to resolved it?

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.IN, pull_up_down = GPIO.PUD_UP)

x = GPIO.input(17)

while x == True:
    print ("ONONONONONONONONONON")

print ("OFF")
share|improve this question

closed as off-topic by Ghanima, lenik, Milliways, Bex, Jacobm001 Feb 6 at 17:33

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be specific to the Raspberry Pi within the scope defined in the help center." – Ghanima, lenik, Milliways, Bex, Jacobm001
If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

up vote 2 down vote accepted

You initialize x with the value of GPIO.input(17) at the time of the initialization. It won't change after that unless you assign something new to it, e.g.:

x = GPIO.input(17)

while x == True:
    print ("ONONONONONONONONONON")
    x = GPIO.input(17)

Now x will be updated for each iteration. You could also just use:

while GPIO.input(17) == True:
    print ("ONONONONONONONONONON")

You should put some kind of passive delay into the loop too, however, or else this will busy loop the processor (i.e., run it up to 100% constantly). How long that can be depends on how you are changing the value of the GPIO; if you are turning it off, 1 or 2 seconds is fine. However, if it is just a momentary change you are looking for (e.g., a button push), the gap will have to be shorter (say 200 ms) so you don't miss it.

share|improve this answer
    
On your first coding it is giving me error of defining value of x, but your second code is working perfectly – Irfan Ghaffar7 Feb 2 at 16:52
    
I'm actually not much of a python user, but that seems strange; x should be mutable. Anyway, the basic logic error is assuming that x is going to change automatically when the value of the GPIO does; there's no way to do that, you actually have to check it via the GPIO.input() function call. – goldilocks Feb 2 at 16:59
    
@goldilocks When x == True is first encountered x is not defined. It's not defined until the x = GPIO.input(17) line. – joan Feb 2 at 17:08
    
@joan Ah, I didn't mean for the previous code to be removed, I was just showing the loop (so I've edited that back in). Good catch. – goldilocks Feb 2 at 17:41

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