So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By btidey
#81099 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;
      case STATE_1 :
         if(counter > 30) {
            state = STATE_2;
            Serial.println("Switching to state 2");
            counter = 0;
      case STATE_2 :
         if(counter > 40) {
            state = STATE_0;
            Serial.println("Switching to state 0");
            counter = 0;

setup {

loop {
   // do other stuff

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.
User avatar
By RichardS
#81102 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.