|
| 1 | +/* |
| 2 | + This example shows how to use a single callback function for multiple threads. |
| 3 | + Each of 5 threads lights up one of 5 LEDs in randomly selected intervals. |
| 4 | + Single callback function is called with a pointer to a data structure, which |
| 5 | + can be used for identifying a pin it needs to light up and thread point to set up |
| 6 | + a new waiting interval. |
| 7 | + |
| 8 | + author: Ivan Koryakovskiy <i.koryakovskiy@gmail.com> |
| 9 | + date: 2017-07-29 |
| 10 | +*/ |
| 11 | + |
| 12 | +#include <Thread.h> |
| 13 | +#include <ThreadController.h> |
| 14 | + |
| 15 | +typedef struct blinkParam |
| 16 | +{ |
| 17 | + Thread *th; |
| 18 | + int pin; |
| 19 | +}; |
| 20 | + |
| 21 | +ThreadController g_controller = ThreadController(); |
| 22 | + |
| 23 | +// Creating 5 controllers, each will call same callback function, |
| 24 | +// but with a different thread pointer as a parameter, and therefore different led |
| 25 | +const int g_th_num = 5; |
| 26 | +Thread *g_th[g_th_num]; |
| 27 | +blinkParam *g_param[g_th_num]; |
| 28 | + |
| 29 | +int nextInterval() |
| 30 | +{ |
| 31 | + // next time call thread after 1-5 seconds |
| 32 | + return 1000 + random(4000); |
| 33 | +} |
| 34 | + |
| 35 | +void blinkLed(void *param) |
| 36 | +{ |
| 37 | + // cast parameters to data structure |
| 38 | + blinkParam *bp = static_cast<blinkParam*>(param); |
| 39 | + |
| 40 | + digitalWrite(bp->pin, HIGH); |
| 41 | + delayMicroseconds(10000); |
| 42 | + digitalWrite(bp->pin, LOW); |
| 43 | + |
| 44 | + bp->th->setInterval(nextInterval()); |
| 45 | +} |
| 46 | + |
| 47 | +void setup() |
| 48 | +{ |
| 49 | + randomSeed(analogRead(0)); |
| 50 | + |
| 51 | + // create five threads to light up pins D9-D13 (Arduino Nano) |
| 52 | + int pin = 9; |
| 53 | + for (int i = 0; i < g_th_num; i++) |
| 54 | + { |
| 55 | + g_param[i] = new blinkParam; |
| 56 | + |
| 57 | + // note that parameter includes placeholders for thread pointer and pin number |
| 58 | + g_th[i] = new Thread(blinkLed, nextInterval(), static_cast<void*>(g_param[i])); |
| 59 | + |
| 60 | + g_param[i]->th = g_th[i]; |
| 61 | + g_param[i]->pin = pin + i; |
| 62 | + |
| 63 | + g_controller.add(g_th[i]); |
| 64 | + |
| 65 | + pinMode(g_param[i]->pin, OUTPUT); |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +void loop() |
| 70 | +{ |
| 71 | + g_controller.run(); |
| 72 | +} |
0 commit comments