jrullan / StateMachine

State machine library for Arduino
MIT License
138 stars 26 forks source link

Transition to any state #13

Open krzychoooo opened 3 years ago

krzychoooo commented 3 years ago

this code work ok

void loop() {
  machine.run();
  machine.transitionTo(S4);
  delay(STATE_DELAY);
}

but this code not work

void state0(){
  Serial.println("State 0");
  if(machine.executeOnce){
    Serial.println("Execute Once");
    digitalWrite(LED,!digitalRead(LED));
  }
  machine.transitionTo(S4);    //**problem**
}
bechtold commented 2 years ago

I can confirm this.

State* HIBERNATE = machine.addState([](){
  if (machine.executeOnce) {
    Serial.println("State: Hibernate");
  }

  // Go to Menu
  if (buttons.pressedA()) {
    Serial.print("Button A pressed ");
    Serial.print(machine.currentState);
    Serial.print(" ");
    Serial.print(machine.transitionTo(MENU));
    Serial.print(" ");
    Serial.println(machine.currentState);
  }

  leds.loop(0, 1);
});

Also tried with machine.transitionTo(2);

In both cases the output is "Button A pressed 0 2 2" but it stays in State 0/HIBERNATE.

krzychoooo commented 2 years ago

Without changing the code of this library, it can be done like this:

State* nextState = nullptr;
void loop() {
  if (nextState)
  {
    machine.transitionTo(nextState);
    nextState = nullptr;
  }
  machine.run(); 
}
...
...
void state0(){
  Serial.println("State 0");
  if(machine.executeOnce){
    Serial.println("Execute Once");
    digitalWrite(LED,!digitalRead(LED));
  }
  nextState = S4;
}