简体   繁体   中英

Execute command only once inside of infinite loop

I have a raspberry pi wich i'm using to monitor an input from the GPIO ports, to do this i need to run an infinite loop.

When i receive a LOW in my input i want to execute a system command usint subprocess.call . The problem is that it executes this command for as long as the input is receiving LOW i have tried this to make it execute only once but i can't make it work.

while 1:
    if (GPIO.input(11) != GPIO.HIGH ):
         puerta_abierta = 1
         if(puerta_abierta == 1 ):
              call(["mpg123", "file.mp3"])
              puerta_abierta = 0
    else:
        puerta_abierta = 0

You could do something like this:

called = False

while True:
    if GPIO.input(11) != GPIO.HIGH:
        if not called:
            call(["mpg123", "file.mp3"])
            called = True

You could also break out of the loop, but that might not be what you intend to happen:

while True:
    if GPIO.input(11) != GPIO.HIGH:
        call(["mpg123", "file.mp3"])
        break

Like this:

puerta_abierta = 0
while 1:
    if (GPIO.input(11) != GPIO.HIGH ):
        puerta_abierta += 1
        if(puerta_abierta == 1 ):
            call(["mpg123", "file.mp3"])
    else:
        puerta_abierta = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM