Timer ======= The earliest timing tools used by humans were hourglasses or water clocks, but after clocks were invented, developed and matured, people began to try using this brand-new timing tool to improve timers, achieving the goal of accurately controlling time. Timers have made many tasks that require human control of time much simpler; quite a few household appliances use timers to control switching or working time. -------------------------------------- .. literalinclude:: /_static/products/mpython-s3/_static/examples/timer/timer_alarm.py :caption: Timer alarm :linenos: Before use, import the mpython, Timer, and music modules:: from mpython import * from machine import Timer import music Define the timer callback function to play the alarm sound:: def playMusic(_): music.play(music.BA_DING,wait=False) Configure the timer, with the mode set to periodic execution and a cycle period of 5 seconds:: tim1.init(period=5000, mode=Timer.PERIODIC,callback=playMusic) .. Note:: ``Timer.init(period=5000, mode=Timer.PERIODIC,callback=None)`` is used to initialize the timer. `mode` can be one of the following: `Timer.ONE_SHOT` means the timer runs once, until the configured channel period expires; `Timer.PERIODIC` specifies that the timer runs periodically at the channel's configured frequency. Get and return the timer's current count value, then display it on the screen:: timerNum=tim1.value() gui.draw_label(text=str("Timer: %d ms" %timerNum), row=1, color=0xffffff, wrap=False) gui.update() .. Note:: The timer.value() function gets and returns the current count value. .. Attention:: You may see that the alarm sounds before the timer reaches exactly 5000ms. This is because there is a delay in the process of transmitting the timing data to the screen.