Search code examples
python-3.xadafruit

I have a code to make a motor run then sleep, then run again, but can't get it to work


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.


Solution

  • 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')