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

asked Jan 1, 2019 at 15:08
3
  • 1
    I didn’t see this last edit to your code, but I would have expected it to work, for what that’s worth. Commented 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. Commented Jan 2, 2019 at 21:34
  • 1
    Ahhh!! Got it. I didn't realize that sleep was probably to catch longer presses. Glad you got it! Commented Jan 2, 2019 at 21:54

1 Answer 1

2
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
answered Jan 1, 2019 at 16:16
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.