0

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?

smeeb
  • 509
  • 2
  • 10
  • 21

2 Answers2

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.

Igor Stoppa
  • 2,125
  • 1
  • 15
  • 20
0

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.

jediz
  • 217
  • 3
  • 7