2

I have the following script which increases the counter variable every time a button is pressed. When counter reaches a certain number i.e. 10 lets say I want an event to trigger.

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

button1=22

GPIO.setup(button1,GPIO.IN,pull_up_down=GPIO.PUD_UP)

counter = 0

while(1):
        if GPIO.input(button1)==0:
                counter = counter + 1
                sleep (0.5)
                print counter
        if counter == 10:
                print("target reached")

GPIO.cleanup()

I've been informed that a simple way to do this would be check the counter each time it changes and then use an if statement to trigger the event. Unfortunately I have a very elementary understanding of programming and have little idea how to do this.

Having researched if statements I came across this one that looked as if it might work -

if counter == 10:
  print("target reached")

It runs without error but doesn't do anything when expected.

My question therefore is how to proceed from here?

Thanks

3
  • I didn’t see this last edit to your code, but I would have expected it to work, for what that’s worth.
    – Eric G
    Jan 2, 2019 at 15:33
  • Thanks Eric. I actually used the code you answered with however I needed to indent the sleep line as the counting was proving a little unpredictable as it was. Seems to be working OK now.
    – Nick C
    Jan 2, 2019 at 21:34
  • Ahhh!! Got it. I didn't realize that sleep was probably to catch longer presses. Glad you got it!
    – Eric G
    Jan 2, 2019 at 21:54

1 Answer 1

1
while(1):
        if GPIO.input(button1)==0:
                counter = counter + 1
                print counter
                if counter == 10:
                    print “I did it!”
                sleep(0.5)  # to prevent multiple counts
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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