3

I need to make a motor run for an amount of time, sleep for an amount of time, then repeat making an infinite loop

from adafruit_motorkit import MotorKit
import time

kit = MotorKit()

while True:
    endtime = time.time() + 60 # runs motor for 60 seconds
    while time.time() < endtime:
            kit.motor1.throttle = 1
            pass
    print('endtime passed')
    time.sleep(10)
    print('done sleeping')

I'm expecting the motor to run for a minute, give the endtime passed message, and sleep for 10 seconds, but the motor never sleeps. I'm new to python so I don't know much about this and any help is appreciated.

Anton Menshov
  • 2,266
  • 14
  • 34
  • 55

1 Answers1

2

You need to set the throttle back to 0 before calling time.sleep.
time.sleep will only pause the process for the given time, you need to explicitly tell the motor to stop moving.

Example:

while True:
    endtime = time.time() + 60 # runs motor for 60 seconds
    while time.time() < endtime:
            kit.motor1.throttle = 1
            pass
    print('endtime passed')
    kit.motor1.throttle = 0
    time.sleep(10)
    print('done sleeping')

Also you don't have to busy-wait the 60 seconds the motor is running, you can just set the throttle on the motor and then call time.sleep:

from adafruit_motorkit import MotorKit
import time

kit = MotorKit()

while True:
    print('running motor')
    kit.motor1.throttle = 1
    time.sleep(60)

    print('pausing 10 seconds')
    kit.motor1.throttle = 0
    time.sleep(10)
    print('done sleeping')
Turtlefight
  • 9,420
  • 2
  • 23
  • 40
  • This works! thanks a lot. one more question though, what would I put in if I want the motor to sleep for 30 minutes? – Levi Hartman Aug 05 '19 at 16:42
  • @LeviHartman if you want your program to sleep for 30 minutes, you can use `time.sleep(30 * 60)` or `time.sleep(1800)` (1800 seconds = 30 minutes) – Turtlefight Aug 06 '19 at 00:17