仅在无限循环内执行一次命令

时间:2013-04-17 02:48:21

标签: python loops raspberry-pi

我有一个覆盆子pi,我用它来监视来自GPIO端口的输入,为此我需要运行一个无限循环。

当我在输入中收到LOW时,我想执行系统命令usint subprocess.call。问题是,只要输入正在接收LOW,它就会执行此命令。我试过这个命令只使它执行一次,但我无法使它工作。

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

2 个答案:

答案 0 :(得分:2)

你可以这样做:

called = False

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

你也可以摆脱循环,但这可能不是你想要发生的事情:

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

答案 1 :(得分:1)

像这样:

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
相关问题