Scheduler_example3.ino 1.8 KB

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