[SOLVED] Serial communication to arduino to switch things

I want to control between 2 modes by writing 1 or 2 to the serial monitor.
But despite any options I cannot set the appropriate variable.

Any help?

const char* const modeText[] = {"Random mode", "Fixed time mode"};
enum GameMode {
  RANDOM_TIME,
  FIXED_TIME,
};

GameMode gamemode;


void setup() {
  // Begin serial communication
  Serial.begin(9600);
  //while (! Serial); // Wait until Serial is ready - Leonardo
  Serial.println("Enter Test mode:");
  Serial.println("Press 1 for random mode");
  Serial.println("Press 2 for fixed time mode");
}

void loop() {
  getTestMode();

}


int getTestMode() {
  if (Serial.available()) {
    char ch = Serial.read();
    Serial.print("I received: ");
    Serial.println(ch);

    if (ch >= '1' && ch <= '2') {
      if (ch == '1') {
        gamemode == RANDOM_TIME;
      } else {
        gamemode == FIXED_TIME;
      }

      Serial.print("Game mode selected = ");
      Serial.println(Serial.println(modeText[gamemode]));

      } else {
        Serial.println("Invalid option");
        }
    }
  }
}

What does your debug output look like? Are you using the Serial Monitor? What are the line ending settings?

@AWOL This is the serial output:

Enter Test mode:
Press 1 for random mode
Press 2 for fixed time mode
I received: 2
Game mode selected = Random mode
13
I received: 1
Game mode selected = Random mode
13

AWOL: What are the line ending settings?

Not sure about what is that.

luispotro: Not sure about what is that.

There is a setting on the Serial monitor for line endings. Whatever is there gets sent after what you type in and send. In your case that's the 13 that's being sent. 13 is ascii code for carriage return.

gamemode == RANDOM_TIME;

Your problem is here. That is a comparison. It equates to true if gamemode is RANDOM_TIME and false otherwise. Fairly useless on its own like that. I assume you meant to assign the value RANDOM_TIME to the variable gamemode.

= is assignment == is comparison

The array indices, for modeText, are 0 and 1, not 1 and 2.

gamemode == RANDOM_TIME;

comparing gamemode and RANDOM_TIME ?

PaulS:
The array indices, for modeText, are 0 and 1, not 1 and 2.

Serial.println(Serial.println(modeText[gamemode]));

gamemode is from the ENUM. He didn’t specify any values for the elements so they’ll be 0 and 1. He’s safe. You’re seeing the characters he’s reading from serial are 1 and 2, but that’s not what he’s using to access the array.

Delta_G:

gamemode == RANDOM_TIME;

Your problem is here. That is a comparison. It equates to true if gamemode is RANDOM_TIME and false otherwise. Fairly useless on its own like that. I assume you meant to assign the value RANDOM_TIME to the variable gamemode.

= is assignment
== is comparison

That was it. I knew the difference all the way but I just wasn’t paying attention to it.

Thanks.