Time control in a while loop

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Dieter.Tepe@live.de
Posts: 8
Joined: Thu Apr 01, 2021 11:47 am

Time control in a while loop

Post by Dieter.Tepe@live.de » Sat Apr 17, 2021 9:19 pm

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.

User avatar
OlivierLenoir
Posts: 60
Joined: Fri Dec 13, 2019 7:10 pm
Location: Picardie, FR

Re: Time control in a while loop

Post by OlivierLenoir » Sun Apr 18, 2021 8:16 am

Did you try machine.Timer()? The documentation is available here.

User avatar
pythoncoder
Posts: 5204
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Time control in a while loop

Post by pythoncoder » Sun Apr 18, 2021 12:21 pm

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.
Peter Hinch

Post Reply