MicroPython Clock Task with RTC and NTP sync



  • Just new to MicroPhyton, I just collected some code pieces in the web to get a "Clock" background task coded with RTC and NTP Sync by just some code lines.
    BTW. No flickering on the display etc.

    Please feel free to comment; need to learn ;-)

    # RTC Clock with NTP Sync for M5STACK
    # References:
    # https://forum.micropython.org/viewtopic.php?t=4329
    # Lobo Version to init RTC and timezone
    # https://forum.micropython.org/viewtopic.php?f=18&t=3553&p=21616&hilit=timezone#p21616
    from m5stack import machine
    from m5stack import lcd
    from time import strftime
    import utime
    import _thread
    
    # move to lowest line on M5STACK display
    lcd.setCursor(0, 227)
    lcd.setColor(lcd.WHITE)
    lcd.print("RTC Clock 1")
    
    # initiate rtc
    rtc = machine.RTC()
    print("Synchronize time from NTP server with TZ=Germany ...")
    rtc.ntp_sync(server="hr.pool.ntp.org", tz="CET-1CEST,M3.5.0,M10.5.0/3")
    
    def watch():
        while True:
            # start position for Date
            if not rtc.synced():                                                            # set color to sync status    
                lcd.setColor(lcd.RED)
            else: 
                lcd.setColor(lcd.GREEN)
    #       lcd.setCursor(92, 227)                                                          # uncomment if you need date on display
    #       lcd.print("Date {}".format(utime.strftime("%Y-%m-%d", utime.localtime())))      # uncomment if needed
            # start position for time only
            lcd.setCursor(213, 227)                                                         # uncomment if date active (see upper lines)
            lcd.print(" Time {}".format(utime.strftime('%H:%M:%S', utime.localtime())))
            utime.sleep(1)
    
    _thread.start_new_thread ("clock",watch, ())


  • Thanks for your example. Where did you found the tz argument ? I cannot find any exhausitive documentation on the function.



  • @ithasu,

    check this link uclibc timezone list



  • yes, already answered, thanks to @simm



  • Just a little comment. I've used this code to have a tiny watch on a M5stick and it did not work till I added the connection to internet. So the code in my case looks like this:

    import wifisetup
    wifisetup.auto_connect()
    from m5stack import *
    from m5ui import *
    ...

    and then the rest of the code is similar, changing timezone and whatnot.

    Thanks for the code and best regards / Fernando



  • @f3rn4nd0d I got "no module named 'wifisetup'" error, and without that, no 'strftime' in time... What am I missing in Mycropython for my M5Stack Gray?

    Thanks for your help.