0

My program is for a raspberry pi project in which I give a user the option to record messages when they press a button. My current goal is to have a while loop give the option of recording by pressing the button and then exiting the loop, and if it is not pressed for 5 seconds it exits the loop.

Here is what my code looks like:

w = True
while w:
    # if the button on the pi is pressed once this while loop begins,
    if GPIO.input(17) == 0:
        print ("Button Pressed")
        sleep(2)
        print ("Explaining recording instructions")
        pygame.mixer.Sound.play(record_s)
        sleep(8)
        print ("Recording")
        record_audio()
        # Exit the loop once message is recorded by pressing the button once more
        if GPIO.input(17) == 0:
            w = False
    # If the button is not pressed for 5 seconds,
    elif sleep(5):
        print ("No input")
        # Exit the loop
        w= False

I have tried several different methods, done lots of googling and looked at similar questions but none of them have worked.

ShaheerL
  • 61
  • 7
  • 1
    Store the time to a variable before starting the loop `start = time.time ()` then check the current time minus the start `if time.time() - start > 5:`. – tgikal Jun 17 '19 at 21:38
  • can someone explain to me `elif sleep(5):` ? sleep returns anything over time? – Grzegorz Krug Jun 17 '19 at 21:59
  • Calling `time.sleep (5)` returns `None` after 5 seconds, so in a if, it would simply never be `True`. – tgikal Jun 17 '19 at 22:20

1 Answers1

0
def run():
    while True:
    # if the button on the pi is pressed once this while loop begins,
        if GPIO.input(17) == 0:
            print ("Button Pressed")

        print ("Explaining recording instructions")
        pygame.mixer.Sound.play(record_s)
        sleep(8)
        print ("Recording")
        record_audio()
        # Exit the loop once message is recorded by pressing the button once more
        if GPIO.input(17) == 0:
            break

def main():
    t = threading.Thread(target=run)
    t.daemon = True
    t.start()
    time.sleep(5)
garyboland
  • 135
  • 12