(SOLVED) Blynk hangs after three minutes of work, only the reset helps

#include <OneWire.h>
#include <Blynk.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>
#include <DallasTemperature.h>
#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#define ONE_WIRE_BUS 2         
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
OneWire  ds(2);                // Завесим датчики на pin 2 (и обязательно подтянем к плюсу 4.7K резистором)
byte i;                        // Любимый счетчик
byte data[8];                  // Сюда попадают данные из датчиков
byte addr[8];                  // Здесь хранятся адреса датчиков
float celsius;                 // Всякая хрень для работы с температурой

char auth[] = "1111111111111111111111111111";

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth);
while (Blynk.connect() == false) {
    // Wait until connected
  }
  sensors.begin();
}
void sendTemps()
{
                                  // Функция последовательно ищет адреса устройств
    if (!ds.search(addr)) {       // и запоминает их в addr. Если очередного устройства не найдено
    ds.reset_search();            // поиск сбрасывается и все начинается сначала
    delay(250);
    return;
    }
    ds.reset();                   // Сбрасываем линию
    ds.select(addr);              // Выбираем найденный адрес
    ds.write(0x44, 1);            // Пишем 0x44 - команда на расчет температуры и 1 - если паразитное питание, если обычное (соединение три провода) то 0.

    delay(1000);                  // Для преобразования при паразитном питании надо 750ms, берем с запасом. Если питание обычное - достаточно 100

    ds.reset();                   // Опять сброс и выбор адреса - так положено по инструкции.
    ds.select(addr);
    ds.write(0xBE);               // Команда датчику, чтобы он начал отдавать данные.

    Serial.print(" ");
    for ( i = 0; i < 9; i++) {    // Читаем 8 байт. А зачем нам все 8? Достаточно первых двух!
    data[i] = ds.read();
    
    Serial.print(" ");
    }

    int16_t raw = (data[1] << 8) | data[0]; // int кодировка сотоит из двух байт, причем каждая единичка значит 0.0625 градуса

    celsius = (float)raw / 16.0;            // Превращаем int во float и делим на 16, что равно умножению на 0.0625, потому что
    Serial.print("First Temperature = ");  // 1 делить на 16 равно 0.0625.
    Serial.println(celsius);
  Blynk.virtualWrite(46, celsius);         // Send temperature to Blynk app virtual pin 46.
}
void loop()
{
  Blynk.run();
  sendTemps();
} 

Your issue is in void loop

Read this article:

The problem is two points. First in the program that can not process
Such amount of information in a short period. The second in my knowledge of programming. I turned to the developers, since the first point of the problem is related to the program. I read about the “library” of SimpleTimer which can solve this problem with the delay command (again, the Blynk problem). But for me, as an absolute beginner in this subject, this is not a solvable problem and the google search engine did not give me anything except as a headache. If you are not so difficult then help, and send me to teach the material part here can everyone. I think if you can help with this problem, it will be useful not only to me, thanks for your understanding.
I apologize for not knowing English, I hope, however, that I was able to convey my thoughts to you.

We all start at the beginning… some, like me, find programming very challenging, but practice helps :wink:

This forum is here to give all users a place to share ideas and quick assistances… but it is not really a place for a programming class :wink:

However, here is an example of how separating loops into timed segments can help stability…

NOTE This is uncompiled and untested!! But try this modification of your sketch… it basically inserts >SimpleTimer< into your loop and runs your sensor loop every two seconds.

I have also reduced a 1 second delay in the middle of your sensor loop. Any blocking delays can affect the overall Blynk communication (that runs in the background) and that can cause the disconnect.

All my modifications have english comments prefaced by *****

#include <SimpleTimer.h>  // ***** include SimpleTimer library.

#include <OneWire.h>
#include <Blynk.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>
#include <DallasTemperature.h>
#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
OneWire  ds(2);                // Завесим датчики на pin 2 (и обязательно подтянем к плюсу 4.7K резистором)
byte i;                        // Любимый счетчик
byte data[8];                  // Сюда попадают данные из датчиков
byte addr[8];                  // Здесь хранятся адреса датчиков
float celsius;                 // Всякая хрень для работы с температурой
char auth[] = "1111111111111111111111111111";

SimpleTimer sensortimer;  // ***** setup a timer called sensortimer.

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth);
  while (Blynk.connect() == false) {
    // Wait until connected
  }
  sensors.begin();

  sensortimer.setInterval(2000L, sendTemps);  // ***** run sendTemps() loop every 2 seconds.

}



void sendTemps()
{
  // Функция последовательно ищет адреса устройств
  if (!ds.search(addr)) {       // и запоминает их в addr. Если очередного устройства не найдено
    ds.reset_search();            // поиск сбрасывается и все начинается сначала
    delay(250);
    return;
  }
  ds.reset();                   // Сбрасываем линию
  ds.select(addr);              // Выбираем найденный адрес
  ds.write(0x44, 1);            // Пишем 0x44 - команда на расчет температуры и 1 - если паразитное питание, если обычное (соединение три провода) то 0.

  // ***** delay(1000);                  // Для преобразования при паразитном питании надо 750ms, берем с запасом. Если питание обычное - достаточно 100
  delay(250);  // ***** not sure what the delay is for, but try to keep any blocking delay as short as possible.

  ds.reset();                   // Опять сброс и выбор адреса - так положено по инструкции.
  ds.select(addr);
  ds.write(0xBE);               // Команда датчику, чтобы он начал отдавать данные.

  Serial.print(" ");
  for ( i = 0; i < 9; i++) {    // Читаем 8 байт. А зачем нам все 8? Достаточно первых двух!
    data[i] = ds.read();

    Serial.print(" ");
  }

  int16_t raw = (data[1] << 8) | data[0]; // int кодировка сотоит из двух байт, причем каждая единичка значит 0.0625 градуса

  celsius = (float)raw / 16.0;            // Превращаем int во float и делим на 16, что равно умножению на 0.0625, потому что
  Serial.print("First Temperature = ");  // 1 делить на 16 равно 0.0625.
  Serial.println(celsius);
  Blynk.virtualWrite(46, celsius);         // Send temperature to Blynk app virtual pin 46.
}



void loop()
{
  Blynk.run();

  //sendTemps();
  sensortimer.run();  // ***** checks timer and will run timer at set intervals (currently every 2 seconds).

}

Thank you very much, I still tried to work with the SimpleTimer library yesterday.
Unfortunately there were too many mistakes and I can not understand whether I’m doing something wrong, or I have to change something in the library. Downloaded and did the instructions on this page https://github.com/schinken/SimpleTimer
Your example gave the same mistakes, I’ll give them below.
SimpleTimer.h:37:24: fatal error: functional.h: No such file or directory
#include <functional.h>
And where to get this library? Google as I do not know.

First, the Blynk libraries should have already included SimpleTimer library in your Arduino repository.

Perhaps remove what you have just installed, and reinstall latest Blynk Libraries from here:

1 Like

I saw that SimpleTimer is in the Blynk library and could not find it there. And everything turns out so easy, he was in the archive. I just added the Blynk library via the Arduino IDE. So many sketches tried and spent searching the SimpleTimer library. Everything was brilliant and simple. Thank you very much “Gunner”.

I have a question on another topic, but with the same sketch. Widget Timer does not work in Blynk. Namely, the stop function, the timer starts normally, but does not turn it off. If you run only the code itself to work with Blynk, then everything works perfectly. What could be the problem?

Well I can’t read your comments, so I am unsure where you are trying to use a Timer Widget. But from looking at the code, particularly at what is missing, you are doing it wrong :wink:

The Timer Widget is essentially an automated Switch… it sends a HIGH or 1 at start and a LOW or 0 at stop. But in order to get that data in your sketch, you need a BLYNK_WRITE() function that gets called every time the status of the Timer changes.

Check the DOC’s and look at the example sketches referenced there to see how it works.

http://docs.blynk.cc/#widgets-controllers-timer

BLYNK_WRITE(Vx)
{
// You’ll get HIGH/1 at startTime and LOW/0 at stopTime.
// this method will be triggered every day
// until you remove widget or stop project or
// clear the stop/start fields of widget
Serial.print("Got a value: ");
Serial.println(param.asStr());
}