arkhipenko / TaskScheduler

Cooperative multitasking for Arduino, ESPx, STM32, nRF and other microcontrollers
http://playground.arduino.cc/Code/TaskScheduler
BSD 3-Clause "New" or "Revised" License
1.22k stars 224 forks source link

passing Taskscheduler reference to Task doesn't work #122

Closed eleson2 closed 3 years ago

eleson2 commented 3 years ago

Code below works, but if I replace Task definition with the commented one, the callback isn't called. Am I wrong in thinking that it should work?

#include <Arduino.h> 
#include "TaskScheduler.h"  // V 3.2.2

void callback(){
  static int a = 0;
  digitalWrite(LED_BUILTIN,a);
  a=1-a;
}

Scheduler ts;
Task blink(1000,TASK_FOREVER,&callback); //,&ts
// Task blink(1000,TASK_FOREVER,&callback,&ts); 

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  ts.init();
  ts.addTask(blink);
  blink.enable();
};

void loop() { ts.execute(); }; 
arkhipenko commented 3 years ago

You need to decide how you want to assign tasks to the chain. Either at the construction time:

Task blink(1000,TASK_FOREVER,&callback,&ts); 

or in the setup():

Task blink(1000,TASK_FOREVER,&callback); //,&ts
...
void setup() {
  ts.addTask(blink);
...

Can not do both. If you do both you are creating a task chain consisting of 2 tasks referencing itself - it's either a crash or a infinite loop somewhere as a result.

eleson2 commented 3 years ago

That, makes perfect sense. But this doesn't run either... I am leaving it there, I know one way to do it. That is enough. I'll solve this another day. Thanks!

#include "TaskScheduler.h" 
void callback(){
  static int a = 0;
  digitalWrite(LED_BUILTIN,a);
  a=1-a;
}

Scheduler ts;
Task blink(1000,TASK_FOREVER,&callback,&ts); 

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  ts.init();
  blink.enable();
};

void loop() { 
   ts.execute(); 
};
arkhipenko commented 3 years ago

I just tested it on my Uno and it does work:

#include "TaskScheduler.h" 
void callback(){
  static int a = 0;
  digitalWrite(LED_BUILTIN,a&1);
  a++;
}

Scheduler ts;
Task blink(1000,TASK_FOREVER,&callback,&ts); 

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
//  ts.init();
  blink.enable();
}

void loop() { 
   ts.execute(); 
}
arkhipenko commented 3 years ago

Do not init the scheduler if you assign it to the Task at creation time. That was the problem. The scheduler was init'ed at the Task creation time.

https://github.com/arkhipenko/TaskScheduler/wiki/API-Task-Scheduler#void-init