Arduino-Scheduler
Portable Collaborative Multi-Tasking Scheduler for Arduino
SchedulerTaskCompletionQueue.ino
Go to the documentation of this file.
1 
25 #include <Scheduler.h>
26 #include <Scheduler/Queue.h>
27 
28 // Check for SparkFun SAMD21 Breakout
29 #if defined(ARDUINO_ARCH_SAMD) && (USB_PID == 0x8D21)
30 #define Serial SerialUSB
31 #endif
32 
33 // Queue of tasks (function pointers)
35 const unsigned int TASKQ_MAX = 8;
37 
38 // Example task: Calculate sum(i): i=0..100
39 volatile unsigned int sum100;
40 
41 void sumTo100()
42 {
43  const unsigned int N = 100;
44  sum100 = 0;
45  for (unsigned int i = 0; i <= N; i++) {
46  sum100 += i;
47  delay(random(200));
48  }
49 }
50 
51 // Example task2: Calculate fac(10)
52 volatile unsigned long int fact10;
53 
54 void factTo10()
55 {
56  const unsigned int N = 10;
57  fact10 = 1;
58  for (unsigned int i = 1; i <= N; i++) {
59  fact10 *= i;
60  delay(random(2000));
61  }
62 }
63 
64 // Example task3: simple background task (push back example)
65 void printAlive()
66 {
67  Serial.print(millis());
68  Serial.println(F(":printAlive::alive..."));
69  Serial.flush();
70  delay(1000);
71 
72  task_t task = printAlive;
73  taskq.push(&task);
74 }
75 
76 void setup()
77 {
78  Serial.begin(57600);
79  while (!Serial);
80  Serial.println(F("SchedulerTaskCompletionQueue: started"));
81  Serial.flush();
82 
83  // Start two worker
86 
87  // Push tasks
88  task_t task;
89  task = sumTo100;
90  Serial.print(millis());
91  Serial.print(F(":setup::push task @sumTo100 = "));
92  Serial.println(int(&sumTo100));
93  taskq.push(&task);
94 
95  task = factTo10;
96  Serial.print(millis());
97  Serial.print(F(":setup::push task @factTo10 = "));
98  Serial.println(int(&factTo10));
99  taskq.push(&task);
100 
101  task = printAlive;
102  Serial.print(millis());
103  Serial.print(F(":setup::push task @printAlive = "));
104  Serial.println(int(&printAlive));
105  taskq.push(&task);
106 
107  // Note: The printAlive task will start when either sumTo100 or
108  // factTo10 are completed as there are only two workers.
109 }
110 
111 void loop()
112 {
113  Serial.print(millis());
114  Serial.print(F(":loop::sum100 = "));
115  Serial.print(sum100);
116  Serial.print(F(", fact10 = "));
117  Serial.println(fact10);
118  delay(1000);
119 }
120 
121 void worker()
122 {
123  task_t task;
124  taskq.pull(&task);
125  task();
126 }
void pull(T *data)
Definition: Queue.h:90
SchedulerClass::func_t task_t
void push(const T *data)
Definition: Queue.h:64
static bool startLoop(func_t taskLoop, size_t stackSize=DEFAULT_STACK_SIZE)
Definition: Scheduler.h:65
void(* func_t)()
Definition: Scheduler.h:31
const unsigned int TASKQ_MAX
Definition: Queue.h:28
volatile unsigned int sum100
volatile unsigned long int fact10
SchedulerClass Scheduler
Definition: Scheduler.cpp:53
Queue< task_t, TASKQ_MAX > taskq