Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino switch with chars

Tags:

arduino

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");
            }

       }
    }
like image 538
Nunyet de Can Calçada Avatar asked Feb 11 '23 06:02

Nunyet de Can Calçada


2 Answers

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.

like image 157
Erik Avatar answered Feb 12 '23 20:02

Erik


Using a buffer of size 2 solved the problem

 serialReceived.substring(0,1).toCharArray(commandChar, 2);
like image 28
Nunyet de Can Calçada Avatar answered Feb 12 '23 20:02

Nunyet de Can Calçada