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() {

void loop() {
    doSomething(&t1, 500);
    doSomethingElse(&t2, 500);

static int doSomething(struct pt *pt, int interval) {

static int doSomethingElse(struct pt *pt, int interval) {

Does anyone see anything that jumps out at them as missing or wrong?

  • What is sleep() ?
    – Majenko
    Jun 12 '15 at 21:46

Check this example: rather than sleep(), it uses PT_WAIT_UNTIL

  while(1) {
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
      timestamp = millis();

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. The while(1) "re-arms" the thread again, once dosomething() finishes. Here is some C switch-while hackery going on. (see dunkels.com/adam/pt/expansion.html)
    – Zhe Hu
    Sep 2 '19 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.