3. Timer Experiment
About 1 min
Routine Code
from machine import Timer
import time
def on_timer(timer):
print("Timer callback invoked")
timer = Timer(Timer.TIMER0, Timer.CHANNEL0,mode=Timer.MODE_PERIODIC, period=100,unit=Timer.UNIT_MS, callback=on_timer, arg=None)
last_time = time.ticks_ms()
try:
while True:
if time.ticks_ms() - last_time >= 200:
last_time = time.ticks_ms()
print("Main loop")
except:
timer.deinit()
del timerExperiment Preparation
- Connect the K210 to your computer via USB.
- Open CanMV IDE and run the routine code above.
Experiment Results
- After running, open the Serial Terminal at the bottom to view debug output. The timer prints every 100 ms and the while loop prints every 200 ms, so for each main loop message you see two timer messages.

Routine Code Explanation
- Import the modules required to run the routine.
from machine import Timer
import time- Define the
on_timercallback function. When the timer triggers, this function runs and prints "Timer callback invoked".
- Define the
def on_timer(timer):
print("Timer callback invoked")- Create a timer instance.
Timer.TIMER0andTimer.CHANNEL0: specify timer 0, channel 0.mode=Timer.MODE_PERIODIC: periodic mode—the timer triggers repeatedly at the set interval.period=100andunit=Timer.UNIT_MS: period is 100 milliseconds.callback=on_timer: set the callback function when the timer triggers.arg=None: no extra arguments passed to the callback.
- Create a timer instance.
timer = Timer(Timer.TIMER0, Timer.CHANNEL0,mode=Timer.MODE_PERIODIC, period=100,unit=Timer.UNIT_MS, callback=on_timer, arg=None)- Get the current millisecond timestamp with
time.ticks_ms()and assign it tolast_timefor subsequent time comparisons.
- Get the current millisecond timestamp with
last_time = time.ticks_ms()- Enter an infinite loop
while True. On each iteration, compare the current timestamp withlast_time. If the difference is at least 200 milliseconds, updatelast_timeand print "Main loop". If an exception occurs during the loop, theexceptblock runs: calltimer.deinit()to stop the timer and release resources, thendel timerto clean up.
- Enter an infinite loop
try:
while True:
if time.ticks_ms() - last_time >= 200:
last_time = time.ticks_ms()
print("Main loop")
except:
timer.deinit()
del timer