Skip to content
Advertisement

Trying to create a timer to pause a loop in python

Here I go messing with timers and motion sensors again.

I have a PIR motion sensor connected to a raspberry pi. I want to have the motion sensor have a cooldown of one minute before it checks for motion again. I’ve been messing around with threading some… but I don’t think I need that for this and would like to keep it simple.

GPIO.setmode(GPIO.BCM)
PIR_PIN = 11
GPIO.setup(PIR_PIN, GPIO.IN)

motion_cooldown = 60
start = 0

while True:
    if(time.time() < start + motion_cooldown):
        print("cooldown")
    else: 
        if PIR_PIN == 1:
            print("motion detected")
            #do some stuff
            start = time.time()
        elif PIR_PIN == 0:
            print("no motion")
            #do some stuff
            start = 0         #reset start to 0 so the loop continues

The current error I’m getting is ” ‘<‘ not supported between instances of ‘builtin_function_or_method and int” I assume that means I can’t compare an int and the time.time() but I swear of done similar before and it worked fine. Any suggestions welcome!

Advertisement

Answer

This is likely to happen if you have not called the function, that is when you do something like start = time.time, but your code does not do that, and it is not reproducible. For pausing the loop you can use time.sleep(60) at the end of the while loop

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement