c++serial-portarduino-uno

Arduino communication via COM Port isnt working


I want my Arduino to light up the LED if he reads "on" in the Serial Port. At Serial.print(serialData); it prints out what he reads but at if (serialData == "on") it wont work.

int led1 = 9;
int led2 = 6;
String serialData;
void setup() {      
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(10);
}

void loop() {
  if (Serial.available() > 0){
    serialData = Serial.readString();
    Serial.print(serialData);
    if (serialData == "on"){
      analogWrite(led1, 255);
    }
    if (serialData == "off"){
      analogWrite(led1, 0);
    }
  }
}

Anybody know, what I'm doing wrong?


Solution

  • There are two issues in your code:

    The solution is to increase the timeout considerably and to use readStringUntil() to read until the newline character is discovered. This is the indication that a full word (or command) has been entered.

    Additionally, the carriage return and line feed need to be trimmed off.

    #include <Arduino.h>
    
    int led1 = 9;
    int led2 = 6;
    String serialData;
    
    void setup() {      
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      Serial.begin(9600);
      Serial.setTimeout(2000);
    }
    
    void loop() {
      if (Serial.available() > 0){
        serialData = Serial.readStringUntil('\n');
        serialData.trim();
        Serial.println(serialData);
        if (serialData == "on"){
          analogWrite(led1, 255);
        }
        if (serialData == "off"){
          analogWrite(led1, 0);
        }
      }
    }