Scheduler_example15_STDFunction.ino 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * TaskScheduler Test sketch - Showing how to use std::function
  3. * to get acces to variables from within the task callback function
  4. *
  5. * Support for std::function is only available for ESP8266 architecture
  6. */
  7. #define _TASK_SLEEP_ON_IDLE_RUN
  8. #define _TASK_STD_FUNCTION // Compile with support for std::function
  9. #include <TaskScheduler.h>
  10. Scheduler ts;
  11. int counter = 0;
  12. class Calculator {
  13. public:
  14. int cumSum = 0; // cumulative sum
  15. Calculator(int b) {
  16. // Pass the this pointer, so that we get access to this->cumSum
  17. // Also pass a copy of b
  18. calculateTask.set(TASK_SECOND, TASK_FOREVER, [this, b]() {
  19. counter++;
  20. Serial.printf("%u. %u: cumSum = %u + %u\t", counter, millis(), cumSum, b);
  21. cumSum += b;
  22. Serial.printf("Resulting cumulative sum: %u\n", cumSum);
  23. });
  24. ts.addTask(calculateTask);
  25. calculateTask.enable();
  26. }
  27. Task calculateTask;
  28. };
  29. Calculator calc1(2);
  30. Calculator calc2(4);
  31. Calculator calc3(8);
  32. // Disable tasks after 10 seconds
  33. Task tWrapper(10*TASK_SECOND, TASK_ONCE, []() {
  34. ts.disableAll();
  35. }, &ts);
  36. /**
  37. * Standard Arduino setup and loop methods
  38. */
  39. void setup() {
  40. Serial.begin(74880);
  41. Serial.println("std::function test");
  42. tWrapper.enableDelayed();
  43. }
  44. void loop() {
  45. ts.execute();
  46. }