Scheduler_example3.ino 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * TaskScheduler Test of OnEnable and OnDisable methods and illustration of using wrapper tasks for timout purposes
  3. *
  4. * A wrapper task runs every 10 seconds and initiates the test case
  5. * Another task is run once for 5 seconds, and serves as a LED blinking timeout - 5 seconds
  6. * Finally, a dedicated task which controls LED is running periodically until stopped, and makes the LED blink with 0.5 to 1 second interval.
  7. *
  8. */
  9. #define _TASK_SLEEP_ON_IDLE_RUN
  10. #include <TaskScheduler.h>
  11. #define LEDPIN 13
  12. Scheduler ts;
  13. // Callback methods prototypes
  14. void WrapperCallback();
  15. bool BlinkOnEnable();
  16. void BlinkOnDisable();
  17. void LEDOn();
  18. void LEDOff();
  19. // Tasks
  20. Task tWrapper(10000L, TASK_FOREVER, &WrapperCallback, &ts, true);
  21. Task tBlink(5000, TASK_ONCE, NULL, &ts, false, &BlinkOnEnable, &BlinkOnDisable);
  22. Task tLED(0, TASK_FOREVER, NULL, &ts, false, NULL, &LEDOff);
  23. void WrapperCallback() {
  24. tBlink.restartDelayed(); // LED blinking is initiated
  25. //every 30 seconds for 5 seconds
  26. }
  27. // Upon being enabled, tBlink will define the parameters
  28. // and enable LED blinking task, which actually controls
  29. // the hardware (LED in this example)
  30. bool BlinkOnEnable() {
  31. tLED.setInterval( 500 + random(501) );
  32. tLED.setCallback( &LEDOn);
  33. tLED.enable();
  34. return true; // Task should be enabled
  35. }
  36. // tBlink does not really need a callback function
  37. // since it just waits for 5 seconds for the first
  38. // and only iteration to occur. Once the iteration
  39. // takes place, tBlink is disabled by the Scheduler,
  40. // thus executing its OnDisable method below.
  41. void BlinkOnDisable() {
  42. tLED.disable();
  43. }
  44. void LEDOn () {
  45. digitalWrite(LEDPIN, HIGH);
  46. tLED.setCallback( &LEDOff);
  47. }
  48. void LEDOff () {
  49. digitalWrite(LEDPIN, LOW);
  50. tLED.setCallback( &LEDOn);
  51. }
  52. // Note that LEDOff method serves as OnDisable method
  53. // to make sure the LED is turned off when the tBlink
  54. // task finishes (or disabled ahead of time)
  55. void setup() {
  56. // put your setup code here, to run once:
  57. pinMode(LEDPIN, OUTPUT);
  58. }
  59. void loop() {
  60. // put your main code here, to run repeatedly:
  61. ts.execute();
  62. }