1

I am trying to make a state machine with if/else. But some of the code does not seem to be executing. I have information being displayed on an LCD screen so I know where it is, and it stays on Todo=1 and does not go to the next state. I have tried using switch/case and it works. But I think it might be better for my project if I use if/else. Can I do this using if/else?

Void loop{
  if (state == PLAY) {
    Todo = 1;
    Mastermachine(Todo);
  } else if (state == TRYAGIN) {

  }
}

void Mastermachine(int Todo) {
  if (Todo == 1) {
    lcd.setCursor(16, 2);
    lcd.print(String(Todo));
    SongSeq[largestindex];
    for (int index = 0; index < largestindex; index++) {
      SongSeq[index]();
    }
    Todo = 2;
  } else if (Todo == 2) {
    for (learnindex = 0; learnindex < largestindex;) {
      MIDI.read();
      if (learnindex >= largestindex) {
        Todo = 3;
      }
      lcd.setCursor(16, 2);
      lcd.print(String(Todo));
    }
  } else  if (Todo == 3) {
    if (array_cmp(learn, note, largestindex, largestindex) == true) {
      largestindex++;
      delay(2000);
      Todo = 1;
    } else {
      delay(2000);
      Todo = 1;
    }
    lcd.setCursor(16, 2);
    lcd.print(String(Todo));
  }
}
  • Consider a switch statement instead of the if/else statements. – Michel Keijzers May 1 '17 at 8:32
  • Make the state a global variable. Todo is lost after each call of MasterMachine() (if you do no introduce a loop). – Mikael Patel May 1 '17 at 13:42
1

Inside Mastermachine(), Todo is a copy whatever is passed as its paramter. Even if you make a global named Todo, it will be 'hidden' by the parameter of the same name. That parameter goes out of scope - disappears - when Mastermachine() exits, including any changes made to it within the function.

There are a few choices to accomplish what you want to do, but the easiest is probably to make a global Todo and get rid of the parameter Todo in Mastermachine(); i.e., make it void Mastermachine(void). Then the name Todo inside the function will refer to the global by that name.

0

Your loop executes continually, always setting the state to 1.....

The called state machine supposedly changes the state, but it get set back to 1 every time the loop executes.

The loop program needs to do the state changes, not the masternachine function.

  • would moving Todo=1 somewhere else fix that issue ? – Hjhk90 May 1 '17 at 1:12
  • If you want to have Todo=1 set only once, place it in setup. – mico May 1 '17 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.