Small computer icon

Arya Jemo | Blog

13 object(s)
No, this website isn't a virus.
File icon

Emulation of threads on Arduino

Emulation of threads on Arduino

They aren’t real threads, that’s why I’m talking about emulation of threads. I’m using the TaskScheduler library:

The library allows you to:

Launch a thread periodically

#include <TaskScheduler.h>

void t2Callback();

Task t2(3000, TASK_FOREVER, &t2Callback);

Scheduler runner;

void t2Callback() {
    Serial.println("Task t2 runs every 3 seconds.");
}

void setup () {
  Serial.begin(9600);
  runner.init();
  runner.addTask(t2);
  t2.enable();
}

void loop () {
/* Any other code that loops forever can go here */
  runner.execute();
}

Launch a thread periodically for a certain time

#define _TASK_SLEEP_ON_IDLE_RUN

#include <TaskScheduler.h>

int ledR=2;


Scheduler ts;

void WrapperCallback();

bool BlinkEnable();
void BlinkDisable();
void LEDON();
void LEDOFF();

/* 1 day = 86,400,000 milliseconds */
Task tWrapper(86400000L,TASK_FOREVER,&WrapperCallback,&ts,true); 

Task tBlink(5000,TASK_ONCE,NULL,&ts,false,&BlinkEnable,&BlinkDisable); 

/* During 5 seconds (tBlink above) */
Task tLED(0,TASK_FOREVER,NULL,&ts,false,NULL,&LEDOFF);

/*--------------------------------*/

void WrapperCallback(){
  tBlink.restartDelayed();
}


/*----------------------------------*/
bool BlinkEnable(){
  tLED.setCallback(&LEDON);
  tLED.enable();
  return true;
}

void BlinkDisable(){
  tLED.disable();
}

void LEDON(){
            digitalWrite(ledR,HIGH);
}

void LEDOFF(){
  
      digitalWrite(ledR,LOW);
      
}

/*----------------------------------*/

void setup() {

pinMode(ledR,OUTPUT);

}

void loop() {

ts.execute();

}