I am trying to get Arduino working with Protothreads and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:
#include <pt.h>
static struct pt t1, t2;
void setup() {
PT_INIT(&t1);
PT_INIT(&t2);
}
void loop() {
doSomething(&t1, 500);
doSomethingElse(&t2, 500);
}
static int doSomething(struct pt *pt, int interval) {
PT_BEGIN(pt);
sleep(100);
PT_END(pt);
}
static int doSomethingElse(struct pt *pt, int interval) {
PT_BEGIN(pt);
sleep(250);
PT_END(pt);
}
Does anyone see anything that jumps out at them as missing or wrong?
2 Answers 2
Check this example: rather than sleep(), it uses PT_WAIT_UNTIL
while(1) {
PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
timestamp = millis();
doSomething();
}
That should be the proto-thread way of waiting: PT_WAIT_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.
The rest looks fine, but I have not tried to run the code.
-
Just to add to the understanding (or confusion), PT_WAIT_UNTIL blocks the execution or "yield" to the other threads. You can see its difference from
sleep
which blocks everyone. Thewhile(1)
"re-arms" the thread again, oncedosomething()
finishes. Here is some C switch-while hackery going on. (see dunkels.com/adam/pt/expansion.html)Zhe Hu– Zhe Hu2019年09月02日 12:37:52 +00:00Commented Sep 2, 2019 at 12:37
Why reinvent the wheel? There are libraries that can do just that for you. For example ArduinoThread . I tried it out and did not need to keep looking further. There are also Wiring and SoftTimer but I did not try those.
sleep()
?