How can I create a loop per seconds in python without Sleep or delay

Asked

Viewed 350 times

-1

I’m developing a programming for EV3, with python, and what I wanted to know is: How can I create a loop per seconds, IE, I want that in a certain time in seconds, the robot does the actions uninterruptedly, so I can not use Sleep or some other delay

def SeguirLinha(lado, tempo, cor):
    if lado == 'D':
        while tempo:
                if sensor() == cor:
                        MotorDireita.run( Velocidade )
                        MotorEsquerda.run( Velocidade )
                else:
                        MotorDireita.run( Velocidade )
                        MotorEsquerda.run( Velocidade * -1 )

What I want to change is there in "while time:" and make the while run only during the time the user decides

1 answer

0


Try using the time library:

from time import time
tempoAEsperar=10 #Espera por 10 segundos


start = time()
while (time()-start < tempoAEsperar):
#seu código aqui

The return of time() is a number representing seconds. As you want to know only the time inside that while, it makes no difference the reference (t=0) used.

This way the while runs until the time difference is greater than the number of seconds specified in the variable tempoAEsperar, while performing the task within him over and over again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.