If statement not working with strings

Hi I'm new to Arduino coding and I have a problem in my project that I don't know how to solve it
I want to receive an SMS and then save the text in a variable and check if it is equal to a string or not
if it is equal I want to send an SMS to my phone number

#include <SoftwareSerial.h> //include SoftwareSerial library for sim800l communication

SoftwareSerial sim800l(5, 4); //define sim800l communication pins

String receivedSMS; //variable to store received SMS

void setup() {
  Serial.begin(9600); //initialize serial communication
  sim800l.begin(9600); //initialize sim800l communication
  delay(1000); //wait for sim800l to initialize
  Serial.println("SIM800L initialized.");
  sim800l.println("AT+CMGF=1"); //set sim800l to text mode
  delay(1000);
  sim800l.println("AT+CNMI=2,2,0,0,0"); //set sim800l to forward received SMS to serial
  delay(1000);
  Serial.println("Ready to receive SMS.");
}

void loop() {
  if (sim800l.available()) { //check if sim800l has received SMS
    receivedSMS = sim800l.readString(); //read received SMS and store in variable
    receivedSMS.trim();
    receivedSMS.toLowerCase();
    Serial.println("Received SMS: " + receivedSMS); //print received SMS to serial monitor
    if (receivedSMS == "direction") { //check if received SMS is "Direction"
      sim800l.println("AT+CMGS=\"+989146764006\""); //replace +1234567890 with the number you want to send the custom text to
      delay(1000);
      sim800l.println("Custom text"); //replace "Custom text" with the text you want to send
      delay(1000);
      sim800l.write(26); //send Ctrl+Z to indicate end of message
      delay(1000);
      Serial.println("Custom text sent.");
    }
    else{
      Serial.println("not match.");
    }
  }
}

The problem is that it always returns "not match.".

From Serial.readString() reference page:

The returned String may contain carriage return and/or line feed characters if they were received.

Perhaps that's the issue?

thank you but I used receivedSMS.trim() in my code.

What do you get in the serial monitor when you print receivedSMS?
What do you get when you print receivedSMS.length()?

00:05:53.717 -> Received SMS: +cmt: "+981234567890","","24/12/07,00:05:49+14"

00:05:53.780 -> direction

00:05:53.780 -> 58

00:05:53.780 -> not match.

Yep, +cmt: "+981234567890","","24/12/07,00:05:49+14 definitely is not equal to "direction"

Oh, thank you very much :pray: :pray:
could you please help me to erase the first part if you know how to do it?

Is it always the same length?
Is the last part that you want to keep always the same length?

Check out .substr()

But even if you get rid of whatever part you are thinking of getting rid of, it still won't match "direction"
"direction" is no where in that String.

Thank you :pray:
Problem solved!

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