Variable declaration in global or in setup()

Hey folks, I'm working on a project which has esp8266, dht11 and a buzzer. I'm also using wifiManager library.

//Default values of tempMin and tempMax
char tempMin[3] = "18"; 
char tempMax[3] = "30";
float f_tempMin;
float f_tempMax;

void setup(){
//Some code here
//I'm getting tempMin and tempMax using wifiManager's custom parameter function. I can successfuly get those values.


//Here I convert char[] to float with using atof() function.
f_tempMin = atof(tempMin);
f_tempMax = atof(tempMax);
}


void loop(){
   t = DHT.getCelsius();
    Serial.println(t);
    h = DHT.getHumidity();
    Serial.println(h);



    if (t < f_tempMin || t > f_tempMax)
    {
      Serial.println("Buzzer Öttü");
      for (int i = 0; i < 1; i++) {
        digitalWrite(buzzer, HIGH);
        Serial.println("BUZZ");
        delay(2000);
        digitalWrite(buzzer, LOW);
        delay(1000);
      }
    }

//Here is more code and esp goes deepSleep
  delay(250);

  ESP.deepSleep(2 * 60 * 1000 * 1000);

}

I tried to explain briefly my code. My problem is in the first lifecycle I can get the values of f_tempMin and f_tempMax as they are entered by user. But in the second lifecycle(After esp wakes up from deep sleep) f_tempMax and f_tempMin are go back to their default values(0).
What I want to do is just like SSID and PASSWORD informations I want to get f_tempMax and f_tempMin only once use them in void loop().
Where and How should I declare those f_tempMax and f_tempMin?

//Some code here

But not HERE.

//I'm getting tempMin and tempMax using wifiManager's custom parameter function. I can successfuly get those values.

SHOW US!

Where and How should I declare those f_tempMax and f_tempMin?

If they are going to be valued in setup() and used in loop(), you only have one choice as to where, and the how should be obvious from what they are to contain. Declaring them as char, and assigning float values to them wouldn't make sense.

erondem:
But in the second lifecycle(After esp wakes up from deep sleep) f_tempMax and f_tempMin are go back to their default values(0).

Why do you think so? You never print them so how do you know?

Sorry I'm being stucked bcs of character limit. Here is my entire code:

#include <FS.h> //
#include <ArduinoJson.h>
#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <PietteTech_DHT.h>     //https://github.com/chaeplin/PietteTech_DHT-8266

//default values of temperatures
char tempMin[3] = "18";
char tempMax[3] = "30";
float f_tempMin;
float f_tempMax;

const int buzzer = 12;


///-----------DHT Initalization

#define DHTPIN 4 // what pin DHT is connected to
#define DHTTYPE DHT11 // DHT 11
//declaration
void dht_wrapper(); // must be declared before the lib initialization

PietteTech_DHT DHT(DHTPIN, DHTTYPE, dht_wrapper);
bool bDHTstarted;       // flag to indicate we started acquisition
void dht_wrapper() {
  DHT.isrCallback();
}
#define DEBUGPRINT
#ifdef DEBUGPRINT
#define DEBUG_PRINT(x)  Serial.println (x)
#else
#define DEBUG_PRINT(x)
#endif

char* topic = "nodes/battery/temp";
char* hellotopic = "nodes/register";
String clientName;
WiFiClient wifiClient;

//cloud and measurements
const char* host = "emoncms.org";
const char* nodeId   = "21";
const char* privateKey = "bc133c987ea418e4ebd18204bea240c0";
ADC_MODE(ADC_VCC);
float h = 0;
float t = 0;
int vcc;
long startMills;
void sendData();

//----------------------------------------------------------
//flag for saving data
bool shouldSaveConfig = false;
//callback notifying us of the need to save config
void saveConfigCallback ()
{
  Serial.println("Should save config");
  shouldSaveConfig = true;
}
//------------------------------------------------------------


void setup(void)
{

  //ESP.eraseConfig();
  pinMode(buzzer, OUTPUT);
  digitalWrite(buzzer, 0);
  startMills = millis();
  // start serial port
  Serial.begin(115200);
  Serial.println();
  
  //SPIFFS.format();
  //------------------File System---------------
  Serial.println("mounting FS...");
  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          //First Way
          strcpy(tempMin, json["tempMin"]);
          strcpy(tempMax, json["tempMax"]);

          //Second Try
          //          tempMin = json["tempMin"];
          //          tempMax = json["tempMax"];

        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read


  //--------------------Added Parameters-----------------

  WiFiManagerParameter custom_tempMin("tempMin", "Enter Min Temp", NULL, 5);
  WiFiManagerParameter custom_tempMax("tempMax", "Enter Max Temp", NULL, 5);


  //------------------------------------------------------
  DEBUG_PRINT();
  WiFiManager wifi; //starts wifi
  //wifi.resetSettings(); //reset wifi
  wifi.setSaveConfigCallback(saveConfigCallback); //set config save notify callback
  wifi.setTimeout(120); //so if it restarts and router is not yet online, it keeps rebooting and retrying to connect
  wifi.addParameter(&custom_tempMin);
  wifi.addParameter(&custom_tempMax);


  if (!wifi.autoConnect("tempSens")) {
    DEBUG_PRINT("timeout - going to sleep");
    DEBUG_PRINT(millis() - startMills);
    

    delay(2000);
    //sleep and try again
    //Sleep Time = Second * 1000000
    Serial.println("First Deep sleep");
    ESP.deepSleep(1 * 60 * 1000 * 1000);
    delay(1000);
  }

  DEBUG_PRINT(millis() - startMills);
  //-------
  //setup hardware



  //read updated parameters
  strcpy(tempMin, custom_tempMin.getValue());
  strcpy(tempMax, custom_tempMax.getValue());
  //----------------------------Save the custom parameters to FS---------
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["tempMin"] = tempMin;
    json["tempMax"] = tempMax;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save

f_tempMin = atof(tempMin);
f_tempMax = atof(tempMax);
    Serial.println("second location of f_tempMin and f_tempMax");
    Serial.println(f_tempMin);
    Serial.println(f_tempMax);
  }

}

void loop(void)
{

  vcc = ESP.getVcc();//readvdd33();
  // original loop

  DEBUG_PRINT(millis() - startMills);

  DEBUG_PRINT("Requesting temperatures...");
  int acquireresult;

  //read twice as the first result is cached from last time. suggested by @chaeplin
  delay(2000);
  DHT.acquireAndWait(100);
  delay(2000);
  acquireresult = DHT.acquireAndWait(100);

  if ( acquireresult == 0 ) {
    t = DHT.getCelsius();
    Serial.println(t);
    h = DHT.getHumidity();
    Serial.println(h);


    //----------------Buzzer Function--------
    Serial.println("second location of f_tempMin and f_tempMax");
    Serial.println(f_tempMin);
    Serial.println(f_tempMax);
    if (t < f_tempMin || t > f_tempMax)
    {
      Serial.println("Buzzer Öttü");
      for (int i = 0; i < 1; i++) {
        digitalWrite(buzzer, HIGH);
        Serial.println("BUZZ");
        delay(2000);
        digitalWrite(buzzer, LOW);
        delay(1000);
      }
    }
    //----------------------------------------


    
    
    sendData();
    DEBUG_PRINT("DONE");
  } else {
    t = h = 0;
    DEBUG_PRINT("Failed");

  }
  //Bağlantı başarılı olduktan sonraki sleep fonksiyonu
  DEBUG_PRINT(millis() - startMills);
  DEBUG_PRINT("Going to sleep");
  delay(250);
  //Sleep Time = Second * 1000000
  Serial.println("Second Deep sleep");
  ESP.deepSleep(2 * 60 * 1000 * 1000);
  //ESP.deepSleep(60 * 1000 * 1000);
  delay(1000);
}


void sendData() {
  DEBUG_PRINT("connecting to ");
  DEBUG_PRINT(host);

  WiFiClient emoClient;

  const int httpPort = 80;
  if (!emoClient.connect(host, httpPort)) {
    DEBUG_PRINT("connection failed");
    return;
  }

  String json = "{temperature:";
  json += t;
  json += ",humidity:";
  json += h;
  json += ",vcc:";
  json += vcc;
  json += "}";

  String url = "/input/post.json?node=";
  url += nodeId;
  url += "&apikey=";
  url += privateKey;
  url += "&json=";
  url += json;

  DEBUG_PRINT("Requesting URL: ");
  DEBUG_PRINT(url);

  // This will send the request to the server
  emoClient.print(String("GET ") + url + " HTTP/1.1\r\n" +
                  "Host: " + host + "\r\n" +
                  "Connection: close\r\n\r\n");
   delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while (emoClient.available()) {
    String line = emoClient.readStringUntil('\r');
    DEBUG_PRINT(line);
  }

  DEBUG_PRINT();
  DEBUG_PRINT("closing connection");


}

And what does the log from serial look like?

septillion:
And what does the log from serial look like?

Here it is. I added some Serial.Println() functions to see what is happening and when is happening.
Just after line "second location of f_tempMin and f_tempMax", you can see the values.
in the first cycle they are 20.00 and 25.00 as I entered.
but in the second cycle they become 0.00 and 0.00

I think problem occurs because in the first cycle void setup() is being executed but in the second cycle, void setup() is not being executed, only void loop() is being executed. So f_tempMin and f_tempMax is going back to their default values which is zero.

If it is my case, how can I solve this?

mounting FS...
mounted file system
reading config file
opened config file
{"tempMin":"20","tempMax":"25"}
parsed json

*WM: Adding parameter
*WM: tempMin
*WM: Adding parameter
*WM: tempMax
*WM: 
*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result: 
*WM: 0
*WM: SET AP STA
*WM: 
*WM: Configuring access point... 
*WM: tempSens
*WM: AP IP address: 
*WM: 192.168.4.1
*WM: HTTP server started
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Request redirected to captive portal
*WM: Handle root
*WM: Scan done
*WM: EVOLUTIONDC
*WM: -73
*WM: Sent config page
*WM: WiFi save
*WM: Parameter
*WM: tempMin
*WM: 20
*WM: Parameter
*WM: tempMax
*WM: 25
*WM: Sent wifi save page
*WM: Connecting to new AP
*WM: Connecting as wifi client...
*WM: Connection result: 
*WM: 3
Should save config
43110
saving config
{"tempMin":"20","tempMax":"25"}second location of f_tempMin and f_tempMax
20.00
25.00
43116
Requesting temperatures...
24.00
85.00
second location of f_tempMin and f_tempMax
20.00
25.00
connecting to 
emoncms.org
Requesting URL: 
/input/post.json?node=21&apikey=bc133c987ea418e4ebd18204bea240c0&json={temperature:24.00,humidity:85.00,vcc:3133}
HTTP/1.1 200 OK

Date: Thu, 08 Jun 2017 12:37:23 GMT

Server: Apache/2.2.22 (Ubuntu)

X-Powered-By: PHP/5.3.10-1ubuntu3.25

Content-Length: 2

Connection: close

Content-Type: application/json



ok

closing connection
DONE
48352
Going to sleep
Second Deep sleep

mounting FS...
mounted file system
reading config file
opened config file
{"tempMin":"20","tempMax":"25"}
parsed json

*WM: Adding parameter
*WM: tempMin
*WM: Adding parameter
*WM: tempMax
*WM: 
*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result: 
*WM: 3
*WM: IP Address:
*WM: 192.168.1.11
16927
16928
Requesting temperatures...
24.00
85.00
[b]second location of f_tempMin and f_tempMax
0.00
0.00[/b]
Buzzer Öttü
BUZZ
connecting to 
emoncms.org
Requesting URL: 
/input/post.json?node=21&apikey=bc133c987ea418e4ebd18204bea240c0&json={temperature:24.00,humidity:85.00,vcc:3134}

closing connection
DONE
24161
Going to sleep
Second Deep sleep

You'll need to post ALL of your code. Use the Reply button, NOT the Quick Reply field. Use the Additional Options link to attach your code, if it exceeds the 9000 character limit.

It looks like your code does re-read the config file, and see the proper values for the temperature limits, after waking up. Without seeing all of your code, it is difficult to see why the data read from the config file is not actually used.

PaulS:
You'll need to post ALL of your code. Use the Reply button, NOT the Quick Reply field. Use the Additional Options link to attach your code, if it exceeds the 9000 character limit.

It looks like your code does re-read the config file, and see the proper values for the temperature limits, after waking up. Without seeing all of your code, it is difficult to see why the data read from the config file is not actually used.

I've post them you see above. Can you have look at them now?

I suspect that you need to create a boolean variable, global in scope, beenSleeping, initialized to false. Set it to true before going to sleep. In setup(), if you have !beenSleeping, set up the WiFiManager. If you have been, there is no reason to do all that stuff with the WiFiManager.

PaulS:
I suspect that you need to create a boolean variable, global in scope, beenSleeping, initialized to false. Set it to true before going to sleep. In setup(), if you have !beenSleeping, set up the WiFiManager. If you have been, there is no reason to do all that stuff with the WiFiManager.

Okay I'm gonna try this. If I understand correctly you say that there is no need use WiFiManager at every cycle. Where I'm confuse is after waking up is setup function executed again?

By the way, I tried to define f_tempMin and f_tempMax in global scope as this;

const float f_tempMin = atof(tempMin);
const float f_tempMax = atof(tempMax);

but this gave me random default value.(default but they are not zero and after every waking up they are still at their same value.) Do you think problem occurs because of WiFiManager or the way I define I define those variables?

const float f_tempMin = atof(tempMin);
const float f_tempMax = atof(tempMax);

you cannot trust that the sequence of anything outside of your functions happens sequentially, so who knows what will happen when this initialization happens?

Since you KNOW tempMin and tempMax, just initialize them:

const float f_tempMin = 18.0;
const float f_tempMax = 30.0;

BulldogLowell:

const float f_tempMin = atof(tempMin);

const float f_tempMax = atof(tempMax);




you cannot trust that the sequence of anything outside of your functions happens sequentially, so who knows what will happen when this initialization happens?

Since you KNOW tempMin and tempMax, just initialize them:



const float f_tempMin = 18.0;
const float f_tempMax = 30.0;

Now I know tempMin and tempMax but as a next step I want to get them from user. So it may vary in the future. I tried many things but still couldn't figure it out.
Basicly I want user to enter tempMin and tempMax ONCE, afterwards I'm gonna need them to trig an alarm.

erondem:
So it may vary in the future.

and yet you have them as const?

const float f_tempMin = 18.0;
const float f_tempMax = 30.0;

BulldogLowell:
and yet you have them as const?

const float f_tempMin = 18.0;

const float f_tempMax = 30.0;

Yes it looks like a mistake. I guess I have problem with saving them. I guess I need to save them as SSID and PASSWORD saved.