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.


Timer alarm
 1from mpython import *
 2from machine import Timer
 3import music
 4from lv_gui import *
 5gui = GUI()
 6
 7def playMusic(_):             # Define the timer callback function, play the alarm sound
 8    music.play(music.BA_DING)
 9
10tim1 = Timer(1)               # Create timer 1
11
12tim1.init(period=5000, mode=Timer.PERIODIC,callback=playMusic)        # Configure the timer, mode is periodic execution, period is 5 seconds
13
14while True:
15    timerNum=tim1.value()
16    gui.draw_label(text=str("Timer: %d ms" %timerNum), row=1, color=0xffffff, wrap=False)
17    gui.update()
18

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.