2

I am working on a project of my own that involves servos on a raspberry pi. I have them spinning when I execute the code but I'd prefer to have the python script kill itself after 10 seconds, rather then having to hit CTRL + C all the time. Is there a way to do this with this particular code?

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()
TGFoxy
  • 39
  • 5

2 Answers2

3

Try something like the following:

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()
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

Try this one

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