Due Multiple Blinks Example

The Scheduler library allows the Arduino Due to manage multiple tasks at the same time.

The Scheduler library allows the Arduino Due to manage multiple tasks at the same time. By setting up a number of other functions that run the same way loop() does, it's possible to have separate looping functions without a dedicated timer.

Hardware Required

  • Arduino Due Board
  • three LEDs
  • three 220 ohm resistors

The Circuit

The anode of the LEDs are connected in series with a 220-ohm resistor to pins 11, 12, and 13 on the Due. Their cathodes connect to ground.

Code

1// Include Scheduler since we want to manage multiple tasks.
2#include <Scheduler.h>
3
4int led1 = 13;
5int led2 = 12;
6int led3 = 11;
7
8void setup() {
9
10 Serial.begin(9600);
11
12 // Setup the 3 pins as OUTPUT
13
14 pinMode(led1, OUTPUT);
15
16 pinMode(led2, OUTPUT);
17
18 pinMode(led3, OUTPUT);
19
20 // Add "loop2" and "loop3" to scheduling.
21
22 // "loop" is always started by default.
23
24 Scheduler.startLoop(loop2);
25
26 Scheduler.startLoop(loop3);
27}
28
29// Task no.1: blink LED with 1 second delay.
30void loop() {
31
32 digitalWrite(led1, HIGH);
33
34 // IMPORTANT:
35
36 // When multiple tasks are running 'delay' passes control to
37
38 // other tasks while waiting and guarantees they get executed.
39
40 delay(1000);
41
42 digitalWrite(led1, LOW);
43
44 delay(1000);
45}
46
47// Task no.2: blink LED with 0.1 second delay.
48void loop2() {
49
50 digitalWrite(led2, HIGH);
51
52 delay(100);
53
54 digitalWrite(led2, LOW);
55
56 delay(100);
57}
58
59// Task no.3: accept commands from Serial port
60// '0' turns off LED
61// '1' turns on LED
62void loop3() {
63
64 if (Serial.available()) {
65
66 char c = Serial.read();
67
68 if (c=='0') {
69
70 digitalWrite(led3, LOW);
71
72 Serial.println("Led turned off!");
73
74 }
75
76 if (c=='1') {
77
78 digitalWrite(led3, HIGH);
79
80 Serial.println("Led turned on!");
81
82 }
83
84 }
85
86 // IMPORTANT:
87
88 // We must call 'yield' at a regular basis to pass
89
90 // control to other tasks.
91
92 yield();
93}

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.