Unable to control digital pin with serial string command

Hi,Please check the below code and share the issue becuase when I send 123 string through serial monitor then Digital pins not changing status

#define FR 9
String a;
void setup() {

Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(FR,OUTPUT);

}

void loop() {

while(Serial.available()) {

a= Serial.readString();// read the incoming data as string
Serial.println(a);
if(a=="123"){
  digitalWrite(FR, HIGH);
    delay(1000);
    digitalWrite(FR, LOW);
  }

}

}

What is the serial monitor line-ending control set to?

How I can set the line end?

It's the control at the bottom of the serial monitor labelled "line-ending".
It should be set to "No line-ending"

Could you guide me if I want to control through string from other software i.e LabVIEW where the line-ending option not available?

The String class has the trim() function to remove non-printable characters (ie. '\r', '\n') from the end of the String and the toLowerCase() and toUpperCase() functions to set the case of the input String.

You will have to determine what Labview uses for a line ending and incorporate the ascii characters of that line ending into your String comparison.
EDIT: I see that groundFungus has recommended the trim function, and that is a goo altlernative

For example if its carriage return + new line then
if(a=="123\r\n"){
If its just a new line then
if(a=="123\n"){

This illustrated the use of the trim() function on the input String. The line endings in serial monitor can be set to anything with this example. If line feed ('\n') or carriage return ('\r) are appended by serial monitor, trim() will remove them. The LED will flash 1 second on receipt of "123", "123\r", "123\n", or "123\r\n".

const byte FR = 13;

void setup()
{
   Serial.begin(9600);
   pinMode(FR, OUTPUT);
}

void loop()
{
   while (Serial.available())
   {
      String a = Serial.readString(); // read the incoming data as string
      a.trim();
      Serial.println(a);
      if (a == "123")
      {
         digitalWrite(FR, HIGH);
         delay(1000);
         digitalWrite(FR, LOW);
      }
   }
}

Thank you very much, Its working

Your post was MOVED to its current location as it is more suitable.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.