0

i need your help.

I need a non-bloking timer, that allows me, in the period it's still counting, doing other tasks. I need this function for my bot and obviously I don't want to block it all times I call this type of function which requires these timers.

So, in the past i used to use in Arduino (c++) the function millis() that in the same configuration seems not working well like

int t0 =0
int t1

void loop(){
t1= millis()
while (t1-t0 < 6000){
Serial.print(Timer!);
t0 = millis();}}

Do you have any advice for me? A code where I can start from? Thanks!

Giuseppe
  • 3
  • 8

2 Answers2

0

The following will print "Timer" for 6 seconds:

import time

start_time = time.time() # returns number of seconds passed since epoch
current_time = time.time()

max_loop_time = 6 # 6 seconds

while (current_time - start_time) <= max_loop_time:
    # do stuff
    print("Timer")
    current_time = time.time()

Adam Minas
  • 136
  • 8
  • Okay, it works but this is not what I managed to do. I needed a timer that does a task only once at expected timings. Just like. "5seconds. In 5 seconds i will print("Timer") then after other 5 seconds print(t"imer") – Giuseppe Jul 20 '21 at 06:51
0

Okay, i found the solution by myself, trying to remember what i previously did on Arduino.

I based this answer from Adam Minas's one, but mine is quite different

So the expected behavior had to be: print(something) every 5 seconds so:

import time

start_time = time.time() # returns number of seconds passed since epoch
#current_time = time.time()
print(start_time)
max_loop_time = 20 # 6 seconds

while True:

    while (time.time() - start_time) > max_loop_time:
    
            print("Timer")
            start_time = time.time()

Then you can stop your while loop with break and other functions like

if == smth : 
    break

    
Giuseppe
  • 3
  • 8