带字符的 Arduino 开关

Arduino switch with chars

我有一个 switch 语句,但似乎不识别字符 C 总是打印默认值

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

       }
    }

此代码似乎可以满足您的要求:

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

  }
}

鉴于你只想要一个char,我改变了commandChar的类型并使用了Stringclass的charAt功能。

如果这有帮助,请告诉我。

使用大小为 2 的缓冲区解决了问题

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