Home > Mobile >  Arduino communication via COM Port isnt working
Arduino communication via COM Port isnt working

Time:04-25

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?

CodePudding user response:

There are two issues in your code:

  • The timeout is set to 10ms. In 10ms, you can at best enter a single character. readString() will return after a single character and the read string will likely be "o", "n", "f".
  • When you hit the RETURN key, a carriage return and a line feed character are also transmitted ("\r\n").

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);
    }
  }
}
  • Related