Scheduler_example02.ino 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #define _TASK_SLEEP_ON_IDLE_RUN
  2. #include <TaskScheduler.h>
  3. Scheduler runner;
  4. // Callback methods prototypes
  5. void t1Callback();
  6. void t2Callback();
  7. void t3Callback();
  8. // Tasks
  9. Task t4();
  10. Task t1(2000, 10, &t1Callback, &runner, true); //adding task to the chain on creation
  11. Task t2(3000, TASK_FOREVER, &t2Callback, &runner, true); //adding task to the chain on creation
  12. Task t3(5000, TASK_FOREVER, &t3Callback);
  13. // Test
  14. // Initially only tasks 1 and 2 are enabled
  15. // Task1 runs every 2 seconds 10 times and then stops
  16. // Task2 runs every 3 seconds indefinitely
  17. // Task1 enables Task3 at its first run
  18. // Task3 run every 5 seconds
  19. // loop() runs every 1 second (a default scheduler delay, if no shorter tasks' interval is detected)
  20. // Task1 disables Task3 on its last iteration and changed Task2 to run every 1/2 seconds
  21. // Because Task2 interval is shorter than Scheduler default tick, loop() executes ecery 1/2 seconds now
  22. // At the end Task2 is the only task running every 1/2 seconds
  23. //
  24. // NOTE that t1 and t2 are affected by the delay() function in the setup() method and are scheduled immediately twice to "catch up" with millis().
  25. void t1Callback() {
  26. Serial.print("t1: ");
  27. Serial.println(millis());
  28. if (t1.isFirstIteration()) {
  29. runner.addTask(t3);
  30. t3.enable();
  31. Serial.println("t1: enabled t3 and added to the chain");
  32. }
  33. if (t1.isLastIteration()) {
  34. t3.disable();
  35. runner.deleteTask(t3);
  36. t2.setInterval(500);
  37. Serial.println("t1: disable t3 and delete it from the chain. t2 interval set to 500");
  38. }
  39. }
  40. void t2Callback() {
  41. Serial.print("t2: ");
  42. Serial.println(millis());
  43. }
  44. void t3Callback() {
  45. Serial.print("t3: ");
  46. Serial.println(millis());
  47. }
  48. void setup () {
  49. Serial.begin(115200);
  50. delay(5000);
  51. Serial.println("Scheduler TEST");
  52. runner.startNow(); // set point-in-time for scheduling start
  53. }
  54. void loop () {
  55. runner.execute();
  56. // Serial.println("Loop ticks at: ");
  57. // Serial.println(millis());
  58. }