I'm trying to assign one string to another inside a if statement, basically how it works is, when the program starts the String is NULL, when I assign a new value to it on the console, the main string receives the value, and I created a temporary string to receive the value too. If I insert the temporary_string = main_string
outside the if statement it will receive the main_string, but if I do so inside the if statement it won't work.
String wifi_name;
void setup() {
Serial.begin(115200);
}
void loop() {
String last_wifi_name;
if (Serial.available()){
wifi_name = Serial.readString();
}
wifi_name.trim();
Serial.print("wifi_name: ");
Serial.println(wifi_name);
Serial.print("last_wifi_name: ");
Serial.println(last_wifi_name);
if (wifi_name == ""){
Serial.println("No value");
}else{
Serial.println("It enters here");
last_wifi_name = wifi_name; //This is not working
}
delay(2000);
}
Output:
wifi_name:
last_wifi_name:
NULL
wifi_name: Trying to assign this
last_wifi_name:
It enters here
The problem is, the last_wifi_name is not being received from the =
The problem is that last_wifi_name
is a local variable. You are setting it with
last_wifi_name = wifi_name;
but at the end of the loop iteration it's destroyed and at the beginning of the next loop iteration a new empty variable is created.