-->
Page 2 of 2

Re: How to execute while loops without Soft WDT Reset initia

PostPosted: Wed Mar 13, 2019 5:33 pm
by btidey
This is the type of structure I commonly use.
Code: Select all#define STATE_0 0
#define STATE_1 1
#define STATE_2 2

int state = STATE_0;
int counter;

void stateMachine() {
   switch(state) {
      case STATE_0 :
         //check whether a state transition should be made
         if(counter > 20) {
            //set state to transition to
            state = STATE_1;
            //do actions on changing state
            Serial.println("Switching to state 1");
            counter = 0;
         }
         break;
      case STATE_1 :
         if(counter > 30) {
            state = STATE_2;
            Serial.println("Switching to state 2");
            counter = 0;
         }
         break;
      case STATE_2 :
         if(counter > 40) {
            state = STATE_0;
            Serial.println("Switching to state 0");
            counter = 0;
         }
         break;
   }
}

setup {
   Serial.begin(115200);
}

loop {
   stateMachine();
   // do other stuff
   counter++;
   delay(100);
}


Note that several different state machines can be called from the main loop to manage different activities. The counter in the example is just a trivial method to show transitions. Normally one might be testing for other conditions. State transitions can also be triggered by other activities. E.g. a button press or a web server call may change state and trigger a sequence of activities through further state transitions.

Re: How to execute while loops without Soft WDT Reset initia

PostPosted: Wed Mar 13, 2019 6:06 pm
by RichardS
You can also use yield(); exactly the same as delay(0);

In theory it delays zero milliseconds, as opposed to the user who said use delay(1) which will delay a fill millisecond...

Its just not as obvious to use delay(0) as it seems wrong.

RichardS