1# check callback feature of the timer class 2 3import pyb 4from pyb import Timer 5 6# callback function that disables the callback when called 7def cb1(t): 8 print("cb1") 9 t.callback(None) 10 11 12# callback function that disables the timer when called 13def cb2(t): 14 print("cb2") 15 t.deinit() 16 17 18# callback where cb4 closes over cb3.y 19def cb3(x): 20 y = x 21 22 def cb4(t): 23 print("cb4", y) 24 t.callback(None) 25 26 return cb4 27 28 29# create a timer with a callback, using callback(None) to stop 30tim = Timer(1, freq=100, callback=cb1) 31pyb.delay(5) 32print("before cb1") 33pyb.delay(15) 34 35# create a timer with a callback, using deinit to stop 36tim = Timer(2, freq=100, callback=cb2) 37pyb.delay(5) 38print("before cb2") 39pyb.delay(15) 40 41# create a timer, then set the freq, then set the callback 42tim = Timer(4) 43tim.init(freq=100) 44tim.callback(cb1) 45pyb.delay(5) 46print("before cb1") 47pyb.delay(15) 48 49# test callback with a closure 50tim.init(freq=100) 51tim.callback(cb3(3)) 52pyb.delay(5) 53print("before cb4") 54pyb.delay(15) 55