By best attempt to provide something of an answer.
You have said:
PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
That is not literally represented in your code, so I take your question to refer
to:
int dist2 = dist1.toInt();
...
PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > (dist2 * 1710));
or a similar section.
When you execute this PT_WAIT_UNTIL
, dist2
contains whatever value you initialized it with in int dist2 = dist1.toInt();
Assuming the condition isn't met, you are exiting runCommand()
by way of PT_WAIT_UNTIL
's return PT_WAITING;
#define PT_WAIT_UNTIL(pt, condition) \
do { \
LC_SET((pt)->lc); \
if(!(condition)) { \
return PT_WAITING; \
} \
} while(0)
The LC_SET
here in PT_WAIT_UNTIL
is being used to generate a label that can be jumped-to later:
#define LC_SET(s) \
do { \
LC_CONCAT(LC_LABEL, __LINE__): \
(s) = &&LC_CONCAT(LC_LABEL, __LINE__); \
} while(0)
Later when you later call runCommand to resume the thread, you execute LC_RESUME
by way of PT_BEGIN(pt);
#define PT_BEGIN(pt) { char PT_YIELD_FLAG = 1; LC_RESUME((pt)->lc)
...
#define LC_RESUME(s) \
do { \
if(s != NULL) { \
goto *s; \
} \
} while(0)
goto *s
here is ultimately jumping to the label created by your use of PT_WAIT_UNTIL
.
You are now back in PT_WAIT_UNTIL
checking the condition with the line if(!(condition))
. That is, you are checking millis() - lastTimeBlink > (dist2 * 1710)
However, what you are probably (more on that below) doing here is reading junk off the stack. dist2
was initialized on a previous execution of runCommand
and its effective lifetime ended when you returned in PT_WAIT_UNTIL
on that prior execution. On this new execution dist2
is uninitialized because you have jumped over its initialization. If you turn the warning level up in File/Preferences you should see something for this.
A number of things can happen at this point, most of them not good. I can't say what the compiler's optimizer will do to this code for certain, but not much would surprised me. It seems likely, just on familiarity with optimizing compilers and what your code looks like, that it is generating code to read dist2
. That may sound like a given, but it isn't when you're doing something undefined. It's possible dist2
has the value from a previous run where you're executing this function in a loop. But it could also have value that makes dist2 * 1710
evaluate to a duration of up to nearly 50 days, causes PT_WAIT_UNTIL
to return from runCommand for so long as you're testing.
Generally, if you're going to use these proto-threads you're going to have to be very careful in thinking about what's actually initialized and what just looks like it is. If you have a PT_whatever
between a non-static local variable initialization or assignment and code where it's used, that's something to examine.