2

我正在做我自己的一个项目,该项目涉及树莓派上的伺服系统。我在执行代码时让它们旋转,但我更愿意让 python 脚本在 10 秒后自行终止,而不是一直按 CTRL + C。有没有办法用这个特定的代码做到这一点?

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(7,GPIO.OUT)

try:
                while True:
                        GPIO.output(7,1)
                        time.sleep(0.0015)
                        GPIO.output(7,0)

                        time.sleep(0.01)

except KeyboardInterrupt:
       print"Stopping Auto-Feeder"
       GPIO.cleanup()
4

2 回答 2

3

尝试以下操作:

import RPi.GPIO as GPIO
import time


stop_time = time.time() + 10

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)

try:
    while time.time() < stop_time:
            GPIO.output(7,1)
            time.sleep(0.0015)
            GPIO.output(7,0)

            time.sleep(0.01)

except KeyboardInterrupt:
    pass

print"Stopping Auto-Feeder"
GPIO.cleanup()
于 2016-11-04T11:57:52.060 回答
0

试试这个

wait = 10
while wait > 0:
    print(wait)
    time.sleep(1)
    wait = wait - 1```

于 2021-09-18T16:05:18.283 回答