Wemos D1 can`t connect to WiFi / Blynk after wake up from deep sleep

Hi there,

I have Wemos D1 mini which checks soil humidity and local temperature and sends data to Blynk. This part of code is doig good job already. Now I decided to add deep sleep functionality to my project.
I faced the following behavior of the board. When you plug usb cable / battery power to the board for the first time, it starts fine, connects to Blynk, do measures and send data to server, disconnects from Blynk and went to sleep. Till that moment everything goes well, but after wake up board can`t connect to Blynk and hangs. Sometime after long hangup Wemos D1 got a crash. Pressing reset button doesnt help, board reach “[xxx] Connecting to MYHOME_WiFi” and always hangs here.

Please find below copy from COM port monitor:


    [4971] Connected to WiFi
    [4971] IP: 192.168.1.196
    [4971] 
        ___  __          __
       / _ )/ /_ _____  / /__
      / _  / / // / _ \/  '_/
     /____/_/\_, /_//_/_/\_\
            /___/ v0.4.8 on Arduino

    [4980] Free RAM: 44432
    [5001] Connecting to blynk-cloud.com:8442
    [5639] <[02|00|01|00] 42a21ec155c640adb7da04f85049ed22
    [5854] >[00|00|01|00|C8]
    [5854] Ready (ping: 25ms).
    [5854] <[11|00|02|00]Hver[00]0.4.8[00]h-beat[00]10[00]buff-in[00]1024[00]dev[00]Arduino[00]build[00]Sep  3 2017 19:55:29[00]
    [6055] <[10|00|03|00|05]vr[00]10
    [6200] >[00|00|02|00|C8]
    Blynk.begin executed...
    [6201] <[0E|00|04|00|1B]Hardware is just connected!
    [6400] >[00|00|04|00|0E]
    [16396] <[06|00|05|00|00]
    [18128] >[00|00|05|00|C8]
    [28129] <[06|00|06|00|00]
    [28192] >[00|00|06|00|C8]
    [38192] <[06|00|07|00|00]
    [38243] >[00|00|07|00|C8]
    [48243] <[06|00|08|00|00]
    [48572] >[00|00|08|00|C8]
    [50003] >[11|1E]a[00|04]
    [50004] >acon
    [58572] <[06|00|09|00|00]
    [58688] >[00|00|09|00|C8]
    Running measurement routine now...
    Current humidity value:8
    [66795] <[14|00|0A|00|07]vw[00]40[00]8
    [66941] <[14|00|0B|00|07]vw[00]45[00]8
    ROM = 28 FF DA 9B B3 16 4 A1
     Chip = DS18B20
     Data = 1 7A 1 4B 46 7F FF C 10 EC  CRC=EC
     Temperature = 0.00 Celsius, 74.53 Fahrenheit
    [68042] <[14|00|0C|00|0C]vw[00]50[00]23.625
    [68103] <[14|00|0D|00|0C]vw[00]55[00]23.625
    Measurements succesfully done!
    Now I'm going to deep sleep for 60 seconds, bye, bye...

    [68255] Disconnected

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x4010f000, len 1384, room 16 
    tail 8
    chksum 0x2d
    csum 0x2d
    v3de0c112
    ~ld
    ь
    Something got me started!
    Blynk.begin...
    [285] Connecting to MYHOME_WiFi


    Exception (29):
    epc1=0x4020f9ab epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000019 depc=0x00000000

    ctx: sys 
    sp: 3ffffd00 end: 3fffffb0 offset: 01a0

    >>>stack>>>
    3ffffea0:  00000001 4022a79f 000002e1 ffffffd3  
    3ffffeb0:  3ffffed0 4020fabb 3ffed95c 00000009  
    3ffffec0:  3ffee108 00000001 3ffeec08 00000064  
    3ffffed0:  00000018 3ffee07c 3ffe9346 3ffe9346  
    3ffffee0:  3fff1027 3ffe93d4 3fff0c34 0000000b  
    3ffffef0:  4021165f 3ffee030 3ffee108 49e2f6e6  
    3fffff00:  00000001 4022bb68 3ffed9e0 401004d8  
    3fffff10:  40211314 402112e8 3ffee048 00000000  
    3fffff20:  402130c5 402112e8 17169e46 40226029  
    3fffff30:  3ffeda40 4021308c 3ffee048 3ffee7a0  
    3fffff40:  402112de 49e27810 60000600 40226271  
    3fffff50:  40211285 3ffee048 3ffee7a0 49e2f6e6  
    3fffff60:  40211738 1716caad 3ffee7a0 60000600  
    3fffff70:  4021bd89 3ffee048 3ffee7a0 49e2ca70  
    3fffff80:  4021bdce 3fffdab0 00000000 3fffdcb0  
    3fffff90:  3ffee7c0 3fffdad0 3ffef298 402056cf  
    3fffffa0:  40000f49 40000f49 3fffdab0 40000f49  
    <<<stack<<<
    )АЬ‹KVЃL	“\'ОНXл

The code as follows:


    // Earth Humidity and Ambient Temperature Sensor.
    #define BLYNK_DEBUG // Optional, this enables lots of prints
    #define BLYNK_PRINT Serial    // Comment this out to disable prints and save space

    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <SPI.h>
    #include <SimpleTimer.h>
    #include <OneWire.h>

    /* Wemos D1 mini pro piouts remark
    A0 - A0
    D0 - GPIO16 to be coonected to RST to utilise ESP.deepSleep([microseconds]* 1000000, [mode])
    D1 - GPIO5
    D2 - GPIO4
    D3 - GPIO0, Pull-up
    D4 - GPIO2, Pull-up, BUILTIN_LED
    D5 - GPIO14
    D6 - GPIO12
    D7 - GPIO13
    D8 - GPIO15, Pull-down
     */

    bool connected = false;
    int WiFi_status = WL_IDLE_STATUS;

    #define HUMIDITY_PIN            A0    // Humidity pin  
    #define BUZZER_PIN              D1    // BUZZER at pin D1/GPIO5
    #define PWR_PIN                 D5    // Power supply pin for humidity sensor
    #define DTEMP_PIN               D6    // DS18B20 digital temperature sensor at pin D6/GPIO12
    #define BLYNK_HMDTY_PIN         V40   // Humidity data display pin to blynk
    #define BLYNK_HMDTY_GRAPH_PIN   V45   // Humidity data graph pin to blynk
    #define BLYNK_DTEMP_PIN         V50   // Temperature data display pin to blynk
    #define BLYNK_DTEMP_GRAPH_PIN   V55   // Humidity data graph pin to blynk

    OneWire ds(DTEMP_PIN);

    // минимальный порог влажности почвы
    #define HUMIDITY_MIN    200
    // максимальный порог влажности почвы
    #define HUMIDITY_MAX    700
    // переменная для хранения показания влажности почвы
    unsigned int humidity = 0;

    //define Time variable
    unsigned long startTime;
    unsigned int sleepSeconds = 60;     // 60 minutes = 3600 seconds

    //define temperature variables
    byte i;
    byte present = 0;
    byte type_s;
    byte data[12];
    byte addr[8];
    float celsiusNow, celsius, fahrenheit;

    //Setup Networks credentials
    char auth[] = "42a21ec155c640adb7da04f85049ed22"; //iGreenery project
    //char ssid[] = "XX_XXXXX";
    char ssid[] = "XXXXXX_XXXX";
    char pass[] = "XXXX";

    //Setup Blynk communications

    /*WidgetLED D0_led(V0);
    WidgetLED D1_led(V1);
    WidgetLED D2_led(V2);
    WidgetLED D3_led(V3);
    WidgetLED D4_led(V4);
    WidgetLED D5_led(V5);
    WidgetLED D6_led(V6);
    WidgetLED D7_led(V7);
    WidgetLED D8_led(V8);
    */
    WidgetLCD lcd(V5);

    BLYNK_CONNECTED(){
      Blynk.syncVirtual(V10); //Sync state of XXXXX button from app.
    }

    BLYNK_WRITE(V10) //Xxxxxxx Button Widget is writing to pin V10
        {
    //      Xxxxxxxv10 = param.asInt(); // assigning incoming value from pin V1 to a variable
        }
    BLYNK_WRITE(V15) //Xxxxxxx Button Widget is writing to pin V15
        {
    //      Xxxxxxxv15 = param.asInt(); 
        }
    BLYNK_WRITE(V20) //Xxxxxxx Button Widget is writing to pin V20
        {
    //      Xxxxxxxv20 = param.asInt(); 
        }
    BLYNK_WRITE(V25) //Xxxxxxx Button Widget is writing to pin V25
        {
    //      Xxxxxxxv25 = param.asInt(); 
        }
    BLYNK_WRITE(V30) //Xxxxxxx Button Widget is writing to pin V30
        {
    //      Xxxxxxxv30 = param.asInt(); 
        }

    // Blynk.virtualWrite(V40, anydata);    //How to send any data or function like uptime (millis() / 1000) from hardware to virtual pin in Blynk

    // Setup command
    unsigned char cmd;
    enum Command
    {
      CMD_NONE,
    };

    SimpleTimer timer;
    //==============================SETUP==============================
    void setup(){
      Serial.begin(74880);
      delay (100);
      Serial.println();
      Serial.print("Something got me started!");
      Serial.println();

    // command initialisation (no command yet)
      cmd = CMD_NONE;

      pinMode(PWR_PIN, OUTPUT);
      pinMode(D0, WAKEUP_PULLUP);

      delay(100);

      Serial.print("Blynk.begin...");
      Serial.println();
      Blynk.begin(auth, ssid, pass);
      Serial.print("Blynk.begin executed...");
      Serial.println();
      Blynk.notify("Hardware is just connected!");
    // trigger sendData function above every x seconds
       timer.setInterval(60000, Measure_Send_Routine);  // 10000 = 10 seconds  (x/1000=seconds)
    }
    //==========================END OF SETUP==============================

    void Measure_Send_Routine(){
      Serial.print("Running measurement routine now...");
      Serial.println();

    // ===================Measure Humidity here===================
      // Power up humidity sensor
       digitalWrite(PWR_PIN, HIGH);
       delay (200);

      // считываем текущее показания датчика влажности почвы
      String serialMessage = "Current humidity value:";
      int humidityNow = analogRead(HUMIDITY_PIN);

      // Power down of humidity sensor
      digitalWrite(PWR_PIN, LOW);
      delay (200);
      
      // если показания текущей влажности почвы
      // не равняется предыдущему запросу 
      if(humidityNow != humidity) {
        // сохраняем текущие показания влажности
        humidity= humidityNow;
        Serial.print(serialMessage += humidity);
        Serial.println();

        // и отправляем показания влажности на BLYNK_HMDTY_PIN и по e-mail
        Blynk.virtualWrite(BLYNK_HMDTY_PIN, humidity);
        Blynk.virtualWrite(BLYNK_HMDTY_GRAPH_PIN, humidity);
        //Blynk.email("motorola_inside@mail.ru", "Subject:Earth humidity is changed to", humidity );
      }
    // ===================Measure Temperature here================
      if ( !ds.search(addr)) {
        Serial.println("Error: No more addresses.");
        Serial.println();
        ds.reset_search();
        delay(250);

        Serial.printf("I'm going to deep sleep anyway for %d seconds, bye, bye...\n\n", sleepSeconds);
        Blynk.disconnect();
        delay (300);
        ESP.deepSleep(sleepSeconds * 1000000, WAKE_RF_DISABLED);
        
        return;
      }
      Serial.print("ROM =");
      for( i = 0; i < 8; i++) {
        Serial.write(' ');
        Serial.print(addr[i], HEX);
      }
      if (OneWire::crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");
        return;
      }
      Serial.println();
      // первый байт определяет чип
      switch (addr[0]) {

      case 0x10:
      Serial.println(" Chip = DS18S20"); // или более старый DS1820
      type_s = 1;
      break;

      case 0x28:
      Serial.println(" Chip = DS18B20");
      type_s = 0;
      break;

      case 0x22:
      Serial.println(" Chip = DS1822");
      type_s = 0;
      break;

      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      } 
      ds.reset();
      ds.select(addr);
      ds.write(0x44); // начинаем преобразование, используя ds.write(0x44,1) с "паразитным" питанием
      delay(1000); // 750 может быть достаточно, а может быть и не хватит 

      // мы могли бы использовать тут ds.depower(), но reset позаботится об этом
      present = ds.reset();
      ds.select(addr); 
      ds.write(0xBE); 
      Serial.print(" Data = ");
      Serial.print(present, HEX);
      Serial.print(" ");

      for ( i = 0; i < 9; i++) { // нам необходимо 9 байт
        data[i] = ds.read();
        Serial.print(data[i], HEX);
        Serial.print(" ");
      }

      Serial.print(" CRC=");
      Serial.print(OneWire::crc8(data, 8), HEX);
      Serial.println();
      // конвертируем данный в фактическую температуру
      // так как результат является 16 битным целым, его надо хранить в
      // переменной с типом данных "int16_t", которая всегда равна 16 битам, 
      // даже если мы проводим компиляцию на 32-х битном процессоре
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // разрешение 9 бит по умолчанию
        if (data[7] == 0x10) {
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // при маленьких значениях, малые биты не определены, давайте их обнулим
        if (cfg == 0x00) raw = raw & ~7; // разрешение 9 бит, 93.75 мс
          else if (cfg == 0x20) raw = raw & ~3; // разрешение 10 бит, 187.5 мс
          else if (cfg == 0x40) raw = raw & ~1; // разрешение 11 бит, 375 мс
        //// разрешение по умолчанию равно 12 бит, время преобразования - 750 мс
      }
      celsiusNow = (float)raw / 16.0;
      fahrenheit = celsiusNow * 1.8 + 32.0;
      Serial.print(" Temperature = ");
      Serial.print(celsius);
      Serial.print(" Celsius, ");
      Serial.print(fahrenheit);
      Serial.println(" Fahrenheit");

      if(celsiusNow != celsius) {
        // сохраняем текущие показания температуры
        celsius= celsiusNow;
        
        // и отправляем показания температуры на BLYNK_DTEMP_PIN и на e-mail
        Blynk.virtualWrite(BLYNK_DTEMP_PIN, celsius);
        Blynk.virtualWrite(BLYNK_DTEMP_GRAPH_PIN, celsius);
        //Blynk.email("motorola_inside@mail.ru", "Subject:Temperature in Greenery is changed to", celsius);

      }
     delay(100);
     Serial.println("Measurements succesfully done!");
     Serial.printf("Now I'm going to deep sleep for %d seconds, bye, bye...\n\n", sleepSeconds);
     Blynk.disconnect();
     delay (300);
     ESP.deepSleep(sleepSeconds * 1000000, WAKE_RF_DISABLED);
    }

    void loop()
    {
      Blynk.run();
      timer.run();
    }

I would appreciate your help.

Why RF_DISABLED ?

I can’t answer why. To be honest i do not know exact meaning of the switch, therefore i assumed this switch prewent D1 to wakeup by RF-RadioFrequency(wifi).

If you can throw me a link with description of it i will appreciate.

As name suggests, wake without WiFi, ergo no Blynk.

Dear Costas,

Thank you, i removed keyword completly and it works now as it should be. 3rd day of uptime just from battery of 2000mAh.
But if can explain the meaning of other keywords, i would appreciate:

WAKE_RFCAL,
WAKE_NO_RFCAL

WAKE_DEFAULT - i suppose has the same meaning as no keyword (wakep up with WiFi is anabled). Actually at my wemos d1 mini this keyword gives an compilation error.

Do you have access to the Google search engine?

1 Like

Yes, I have, but there is no clear explanation. only enumeration that such keywords exist.
Okay, never mind, thank you anyway. topic is closed.