Q:

Contiki help: Cannot understand the variable behavior

I have the following Contiki code where I am just trying to toggle the LEDs based on a variable 'i' being odd or even:
while (1) {
    etimer_set(&et, CLOCK_SECOND * 2);
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
    i++;
    printf("i is %2d\n",i);
    if ((i % 2) == 0) {
        printf("Now go green.......\n");
        leds_on(LEDS_GREEN);
        leds_off(LEDS_RED);
    } else {
        printf("Reds again.......\n");
        leds_on(LEDS_RED);
        leds_off(LEDS_GREEN);
    }
}

The behavior when I run it on the CC2650 is quite strange.  It always print i is 1.  i has been declared above this code. 
If I place the timer set code of two lines at the beginning of the loop however, i counts all the way and has no problem.  But in that case, the LED toggles cannot be seen.  
What am I missing here? 
Please help

A:

Contiki uses protothreads to implement processes.  A protothread does not have its own stack, therefore protothread functions do not properly support local variables.  In particular, you can't rely on the value of local variables being preserved across yield points.  And macros such as PROCESS_WAIT_EVENT_UNTIL may yield the execution to another protothread, so that's your problem. 
You need to declare i with the keyword static to preserve its value throughout all of the protothread body.  Otherwise you get undefined behaviour. 
For example, this is bad:
int i ;
i = 13;
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
printf("i=%d\n", i); // undefined behaviour

While this is ok:
int i ;
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
i = 13;
printf("i=%d\n", i); // prints 13

And also this, as i here is placed in one of the global memory sections:
static int i ;
i = 13;
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));
printf("i=%d\n", i); // prints 13

