2

I am trying to make a 'game' while learning about both Python and GPIO on the Raspberry Pi. This is what I have ATM:

while playing == 1:
        if (GPIO.input(9) == 0):
            GPIO.output(18, GPIO.LOW)
            print("Well done!!")
            time.sleep(1)
        else:    
            print("Wrong!")
            lives = lives - 1
            time.sleep(1)
        playing = 0

Now, my problem is that the program is hitting the if statement and is going straight to the else (as you would expect), however, I want the program to wait on the first part of the if statement for a second, then go to the else.

Thanks in advance!

Sam
  • 23
  • 5
  • 1
    I might be misunderstanding something. You want that code to wait for 1 second before running the `if/else` block? Because if that's the case, it's just a matter of putting the `time.sleep(1)` right before the `if` (or right under the `while playing == 1:`, but this is probably not that what you want, right? – Savir Feb 22 '15 at 17:38
  • 1
    You need to state the question more clearly. In doing so, you may even solve the problem – Johan Lundberg Feb 22 '15 at 17:38

1 Answers1

1

Perhaps you could rewrite it like so:

while playing == 1:
   for _ in range(10):
       if GPIO.input(9) == 0:
           GPIO.output(18, GPIO.LOW)
           print("Well done!!")
           break
       time.sleep(0.1)
   else:    
       print("Wrong!")
       lives = lives - 1

This polls the GPIO pin ten times 100ms apart. The else is hit if the GPIO pin stays high throughout the ten attempts.

(If you haven't come across Python's for-else construct, see Why does python use 'else' after for and while loops?.)

Alternatively, you could use GPIO module's more advanced features, such as edge detection and callbacks. See the documentation.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012