0
#include <SoftwareSerial.h>
SoftwareSerial my (D6,D7); //(Rx,Tx)
String msg;

void setup() {
Serial.begin(115200);
my.begin(9600);
}

void gas()
{
  
  Serial.println(msg);
  if (msg == "0")
  {
    Serial.println("Gas Leakage !!");
  }
  if(msg == "1") {
    delay(1);
  } 
}
 
void loop() {
  
  msg = my.readStringUntil('\n');
  gas(); 
}

//I am using software serial to exchange data from Arduino UNO to NodeMCU, i am receiving the data correctly but the "if statement condition" is not working with it. how can i make the if statement work?

7
  • Maybe you also have an \r in your string. How exactly are you sending the message?
    – chrisl
    Sep 13 '20 at 15:44
  • my problem solved by changing the if (msg == "0") with if (msg[0] == '0') ,, but I don't know why? Sep 13 '20 at 15:47
  • 1
    I would guess exactly the reason I stated above
    – chrisl
    Sep 13 '20 at 15:49
  • 1
    what does that terminator \r \n means? in serial communication ? Sep 13 '20 at 15:50
  • 1
    yes I am using Serial.println() Sep 13 '20 at 16:02
2

You are using Serial.println() to send the message. That function will add the combination \r\n as line ending to your message, which are the ASCII codes for return carriage and newline.

In your receiving code, you read until \n, so your message now reads "0\r", which is of course not equal to "0". Thus the if condition will never trigger.

When using msg[0] == '0' you are taking the first character out of the string and compare that to the character '0' (especially note the difference between "0", which is a string, and '0', which is a single character). Since you are only using the first character of the string, the \r is out of the picture; you aren't using it.

What to do now?

  • You could send your message only with the \n character as line ending. For this only use Serial.print() instead of Serial.println() and add the line Serial.print("\n"); directly after you send your message.

  • You could write your own read-until code and just ditch every occurrence of the \r character.

  • You can use msg.trim() to remove any white space characters at the start or end of your string, including the \r at the end. Then you can use the code, that you already wrote.


Note, that using Strings on an Arduino is mostly considered evil. Especially if you want to use the code for a longer period or you are using String very often. The memory for a String is allocated dynamically, which can easily lead to heap fragmentation. For a better and longer explanation, look at The Evils of Arduino Strings, a blog entry from Majenko, who is one of our biggest contributors here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.