timer_callback.py 1001 B

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