Page 1 of 1

Time control in a while loop

Posted: Sat Apr 17, 2021 9:19 pm
by Dieter.Tepe@live.de
My program:

Code: Select all

import machine
import utime
import sys
letzte_zeit = 0
diff_erreicht = 0

def zeit_diff(schlafen):
    global letzte_zeit
    if utime.ticks_diff(utime.ticks_ms(), letzte_zeit) >= schlafen:
        letzte_zeit = utime.ticks_ms()
        diff_erreicht = 1
        return(diff_erreicht)

while True:
    print("I am the main program")

    if zeit_diff(2) == 1:
          print("do something when the time period-1 is up")
          diff_erreicht = 0
          
#how can I program this now, so that the next If statements are executed correctly.          
    
    if zeit_diff(1000) == 1:
          print("do something when the time period-2 is up")
          diff_erreicht = 0

    if zeit_diff(2000) == 1:
          print("do something when the time period-3 .... is up")
          diff_erreicht = 0

I would like to do various tasks in the main program, time-controlled.
How do I have to change my subroutine so that I can query the If queries multiple times in a time-controlled manner.
Am still a newbie.

Re: Time control in a while loop

Posted: Sun Apr 18, 2021 8:16 am
by OlivierLenoir
Did you try machine.Timer()? The documentation is available here.

Re: Time control in a while loop

Posted: Sun Apr 18, 2021 12:21 pm
by pythoncoder
I would look at uasyncio. There is a learning curve, but in most cases it's the easiest way to manage tasks involving time delays. See the docs and this tutorial.