Scheduler_example03.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #ifndef LED_BUILTIN
  12. #define LED_BUILTIN 13 // define appropriate pin for your board
  13. #endif
  14. Scheduler ts;
  15. // Callback methods prototypes
  16. void WrapperCallback();
  17. bool BlinkOnEnable();
  18. void BlinkOnDisable();
  19. void LEDOn();
  20. void LEDOff();
  21. // Tasks
  22. Task tWrapper(10000L, TASK_FOREVER, &WrapperCallback, &ts, true);
  23. Task tBlink(5000, TASK_ONCE, NULL, &ts, false, &BlinkOnEnable, &BlinkOnDisable);
  24. Task tLED(0, TASK_FOREVER, NULL, &ts, false, NULL, &LEDOff);
  25. void WrapperCallback() {
  26. tBlink.restartDelayed(); // LED blinking is initiated
  27. //every 30 seconds for 5 seconds
  28. }
  29. // Upon being enabled, tBlink will define the parameters
  30. // and enable LED blinking task, which actually controls
  31. // the hardware (LED in this example)
  32. bool BlinkOnEnable() {
  33. tLED.setInterval( 200 + random(801) );
  34. tLED.setCallback( &LEDOn);
  35. tLED.enable();
  36. return true; // Task should be enabled
  37. }
  38. // tBlink does not really need a callback function
  39. // since it just waits for 5 seconds for the first
  40. // and only iteration to occur. Once the iteration
  41. // takes place, tBlink is disabled by the Scheduler,
  42. // thus executing its OnDisable method below.
  43. void BlinkOnDisable() {
  44. tLED.disable();
  45. }
  46. void LEDOn () {
  47. digitalWrite(LED_BUILTIN , HIGH);
  48. tLED.setCallback( &LEDOff);
  49. }
  50. void LEDOff () {
  51. digitalWrite(LED_BUILTIN , LOW);
  52. tLED.setCallback( &LEDOn);
  53. }
  54. // Note that LEDOff method serves as OnDisable method
  55. // to make sure the LED is turned off when the tBlink
  56. // task finishes (or disabled ahead of time)
  57. void setup() {
  58. // put your setup code here, to run once:
  59. pinMode(LED_BUILTIN , OUTPUT);
  60. }
  61. void loop() {
  62. // put your main code here, to run repeatedly:
  63. ts.execute();
  64. }