Scheduler_example15_STDFunction.ino 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. #define _TASK_STD_FUNCTION // Compile with support for std::function
  6. #include <TaskScheduler.h>
  7. Scheduler ts;
  8. class Calculator {
  9. public:
  10. size_t cumSum = 0; // cumulative sum
  11. Calculator(size_t b) {
  12. // Pass the this pointer, so that we get access to this->cumSum
  13. // Also pass a copy of b
  14. calculateTask.set(TASK_SECOND, TASK_FOREVER, [this, b]() {
  15. Serial.printf("cumSum = %u + %u\n", cumSum, b);
  16. cumSum += b;
  17. Serial.printf("Resulting cumulative sum: %u\n", cumSum);
  18. });
  19. ts.addTask(calculateTask);
  20. calculateTask.enable();
  21. }
  22. Task calculateTask;
  23. };
  24. Calculator calc1(2);
  25. Calculator calc2(4);
  26. Calculator calc3(8);
  27. // Disable tasks after 10 seconds
  28. Task tWrapper(10*TASK_SECOND, TASK_ONCE, []() {
  29. ts.disableAll();
  30. }, &ts);
  31. /**
  32. * Standard Arduino setup and loop methods
  33. */
  34. void setup() {
  35. Serial.begin(115200);
  36. Serial.println("std::function test");
  37. tWrapper.enableDelayed();
  38. }
  39. void loop() {
  40. ts.execute();
  41. }