Nuñito Calzada
Nuñito Calzada

Reputation: 2106

Arduino switch with chars

I have a switch statement, but It seems that don't recognize the character C as always print default

void setup() {
   Serial.begin(9600);
   Serial.println("Serial conection started, waiting for instructions...");
}
    String serialReceived;
    char commandChar[1];

    void loop() {

      if(Serial.available() > 0) {

            serialReceived = Serial.readStringUntil('\n');
            serialReceived.substring(0,1).toCharArray(commandChar, 1);


            switch (commandChar[0]) {
             case 'C':
                 Serial.print("Arduino Received C");
                 break;
                default:
                 Serial.print("default");
            }

       }
    }

Upvotes: 4

Views: 24684

Answers (2)

Nuñito Calzada
Nuñito Calzada

Reputation: 2106

Using a buffer of size 2 solved the problem

 serialReceived.substring(0,1).toCharArray(commandChar, 2);

Upvotes: 1

Erik
Erik

Reputation: 2213

This code seems to do what you want:

void setup() {
   Serial.begin(9600);  
   Serial.println("Serial conection started, waiting for instructions...");
}

String serialReceived;
char commandChar;

void loop() {

    if(Serial.available() > 0) {

      serialReceived = Serial.readStringUntil('\n');
      commandChar = serialReceived.charAt(0);

      switch (commandChar) {
         case 'C':
             Serial.print("Arduino Received C");
             break;
         default:
             Serial.print("default");
      }

  }
}

Given that you only want a single char, I changed the type of commandChar and used the charAt function of the String class.

Let me know if this helps.

Upvotes: 8

Related Questions