Variable IP disappearing

Hello all. I’m building a program that measures the air quality (like gas, temperature, humidity, etc…) and sending it to an ESP8266-01 so I can access these values on a Smartphone App.

The problem is, this programme does to much stuff like sending SMS (if necessary), reading values, sending these values via Serial to the ESP, and involve, as well, data treatment (per example, when I send data via Serial to the ESP8266, I add a “!” at the end of the value and a “;” in the final of it, for example “!25;”, so the ESP knows what is trash and what is not, in the case I receive other random characters with the message.

I apologise for digressing, so the real problem is, with all of these instructions, I think I’m running out of memory on my ATmega328p-pu, causing it to clear variable values, and, sometimes, crash (the general use of global dynamic memory use is caused by the OLED LCD 128x64 I2C SH1106 - “Adafruit_SH1106.h”).

For example, on the code below, when setting the variable IP, in case of the function returns true, it sets while in the function but then, it just disappears.

bool validateIp() {
  bool state = true;
  const PROGMEM unsigned long currentTime = millis();
  Serial.print(ip);
  while(!Serial.available()) {
    // Wait
    if (millis() - currentTime > 3000) {
      state = false;
      break;
    }
  }
  if (state == true) {
    const char res = (char)Serial.read();
    switch (res) {
      case '1':
        return true;
        break;
      case '0':
        return false;
        break;
    }
  }
  
}

// CODE
switch (resNum) {
        case '5':
          phoneNumber = response.c_str();
          Serial.print(phoneNumber);
          break;
        case '6':
          ip = response.c_str();
          const bool res = validateIp();
          if (res == true) {
            ip = response.c_str();
          } else {
            ip = "";
          }
          // Here, even if the function returns true, the IP value defined 3 lines above disapears
          break;
      }
// CODE

By the way, the sketch is using 69% of the program storage space and global variables are using 82% of the dynamic memory, which probably is causing the failures.

The whole code is attached here, in case you want to check it out.

Thanks in advance

__MQ_4_7_final_teste2.ino (9.86 KB)

ip is a pointer that initially points to a zero length string. Later in loop, you create a String object response and sometimes you point the ip pointer to a C string provided by that String. That C string will be freed when the String goes out of scope and now ip is pointing to memory it doesn't own and which will likely be reused.

You need to give ip some memory of its own and you need to strcpy the C string from response to it if you want it to persist.

Better too, especially if you're low on memory, to avoid String objects altogether.