My project keeps going offline

Hi I was hoping someone could explain to me why my project keeps going offline, ive added a re-connection sketch to my program but it doesnt seem to be working anymore. It was running well for about 2 weeks and now it seems to go offline every second day sometimes twice a day. Im running a arduino mega with ethernet shield Im not a fan of the ethernet shield but its all I got at the moment and it shouldnt be causing the program to go offline so often. please look at my sketch and tell me if theres anyway to improve its functionality

  

#define BLYNK_PRINT Serial

#include <SPI.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>

#define W5100_CS  10
#define SDCARD_CS 4


char auth[] = "     ";


#define waterLevel_trigger 3      // Water level sensor
#define waterLevel_echo 9
#define hydroTrig 5      // Water level sensor
#define hydroEcho 6
#define MAX_DISTANCE 450
#define PI 3.1415926535897932384626433832795

#define TdsSensorPin A15
#define VREF 5.0 // analog reference voltage(Volt) of the ADC
#define SCOUNT 30 // sum of sample point

#include "DFRobot_PH.h"
#include <EEPROM.h>

#define PH_PIN A14
float voltage,phValue,temperature = 25;
DFRobot_PH ph;

#include <OneWire.h>
#include <DallasTemperature.h>
#define waterTemp 7

OneWire oneWire(waterTemp);

DallasTemperature sensors(&oneWire);

 float Celcius=0;
 float Fahrenheit=0;
                       
#include <DHT.h>
#define DHT1 2 // What digital pin we're connected to        
#define DHT2 8             
#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE2 DHT11   // DHT 11


DHT dht1(DHT1, DHTTYPE);
DHT dht2(DHT2, DHTTYPE2);

BlynkTimer timer;
  
//=============================================================================================

const int Diameter1 = 40;
const int Depth1 = 56;
const int Diameter2 = 28;
const int Depth2 = 26;
const int Area1 = PI * ((Diameter1 / 2) * (Diameter1 / 2));
const int Area2 = PI * ((Diameter2 / 2) * (Diameter2 / 2));

int Litres1, Litres2, distance1, distance2, WaterDepth1, WaterDepth2;
    
void sendWaterlevel()
{
 long duration, distance1;
  digitalWrite(waterLevel_trigger, LOW);  
  delayMicroseconds(2); 
  
  digitalWrite(waterLevel_trigger, HIGH);
  delayMicroseconds(10); 
  
  digitalWrite(waterLevel_trigger, LOW);
  duration = pulseIn(waterLevel_echo, HIGH);
  distance1 = (duration/2) / 29.1;

  if (distance1 >= Depth1 || distance1 == 0 ) distance1 = Depth1;

   WaterDepth1 = Depth1 - distance1;
   Litres1 = (Area1 * WaterDepth1) / 1000;
 
  Serial.print(distance1);
  Serial.println("Centimeter");
  Serial.println("Tank 1 water depth: " + String(WaterDepth1));     //print depth
  Blynk.virtualWrite(V1, WaterDepth1);
  Serial.println("Tank 1 Litres: " + String(Litres1));                         //print litres
  Blynk.virtualWrite(V8, Litres1);

  delay(200);  
}

//=============================================================================================                                  

void sendHydroLevel()
{
 long duration, distance2;
  digitalWrite(hydroTrig, LOW);  
  delayMicroseconds(2); 
  digitalWrite(hydroTrig, HIGH);
  delayMicroseconds(10); 
  

  digitalWrite(hydroTrig, LOW);
  duration = pulseIn(hydroEcho, HIGH);
  distance2 = (duration/2) / 29.1;

  if (distance2 >= Depth2 || distance2 == 0 ) distance2 = Depth2;

   WaterDepth2 = Depth2 - distance2;
   Litres2 = (Area2 * WaterDepth2) / 1000;
 
  Serial.print(distance2);
  Serial.println("Centimeter");
  Serial.println("Hydro tank water depth: " + String(WaterDepth2));     //print depth
  Blynk.virtualWrite(V12, WaterDepth2);
  Serial.println("Hydro tank Litres: " + String(Litres2));                         //print litres
  Blynk.virtualWrite(V13, Litres2);

  delay(200);  
}
                              
//=============================================================================================   

void sendDHT1Sensor()
{
  float h = dht1.readHumidity();
  float t = dht1.readTemperature();    // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT1 sensor!");
    return;
}
                                      // You can send any value at any time.
                                     // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}

//=============================================================================================

void sendDHT2Sensor()
{
  float h = dht2.readHumidity();
  float t = dht2.readTemperature();    // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT2 sensor!");
    return;
}
                                      // You can send any value at any time.
                                     // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V14, h);
  Blynk.virtualWrite(V15, t);
}

//=============================================================================================


 const int dry = 589;              // Moisture sensor reading while dry
 const int wet = 295;             // Moisture sensor reading while wet
  

void sendMoisture1()
{
  int sensorVal0 = analogRead(A0);
  
  int percentageHumidity0 = map(sensorVal0, wet, dry, 100, 0);
  Blynk.virtualWrite(V4, percentageHumidity0);
  Serial.print(percentageHumidity0);
  Serial.println("%");
  delay(100);
}

//=============================================================================================

void sendMoisture2()
{
  int sensorVal1 = analogRead(A1);
  
  int percentageHumidity1 = map(sensorVal1, wet, dry, 100, 0);
  Blynk.virtualWrite(V3, percentageHumidity1);
  Serial.print(percentageHumidity1);
  Serial.println("%");
  delay(100);
}

//=============================================================================================

void sendMoisture3()
{
  int sensorVal2 = analogRead(A2);
  
  int percentageHumidity2 = map(sensorVal2, wet, dry, 100, 0);
  Blynk.virtualWrite(V10, percentageHumidity2);
    Serial.print(percentageHumidity2);
  Serial.println("%");
  delay(100);
}

//=============================================================================================

  void sendMoisture4()
{
  int sensorVal3 = analogRead(A3);
  
  int percentageHumidity3 = map(sensorVal3, wet, dry, 100, 0);
  Blynk.virtualWrite(V11, percentageHumidity3);
  Serial.print(percentageHumidity3);
  Serial.println("%");
  delay(100);
}

//=============================================================================================

float corrective = 20.55; // calculate and change this value to calibrate
float averageValue = 0.00; // transit area, used in the calculations
int tabval[50]; // memorization table of 10 consecutive readings.
int temp = 0; // transit area, used in the sorting loop of read values
byte index = 0; // index table scrolling values
byte index1 = 0; // index used in the sort loop of the read values
float sumValues = 0; // sum of the 6 intermediate values ​​detected on the analog pin 0
float PHaverage = 0; // PH calculated on the average of the voltages detected on pin 0

void sendPhSensor()
{
    for (index = 0; index < 50; index++) //  stores 50 readings
 {
 tabval[index] = analogRead(A5);
 delay(60);
 }
 //
//rather interesting routine sorts values in tabval array, putting them in order, from lowest to
//highest.
for (index = 0; index < 49; index++)
 {
for (index1 = index + 1; index1 < 50; index1++)
 {
 if (tabval[index] > tabval[index1])
 {
 temp = tabval[index];
 tabval[index] = tabval[index1];
 tabval[index1] = temp;
 }
 }
 }
 sumValues = 0; // resets the sum area of ​​the values ​​in advance
 for (int index = 10; index < 39; index++) // when calculating the average, consider only the values
 // intermediate, from the tenth to the thirty-ninth position in the tabval table.
 sumValues += tabval[index]; // average of the six intermediate values ​​stored in tabval
 averageValue = (float)sumValues * 5.0 / 1024 / 30; // average voltage on the analog pin 0
 PHaverage = -5.70 * averageValue + corrective; // PH calculation, from a formula found on the net
 Serial.print("PH detected = ");
 Serial.println(PHaverage);
 Blynk.virtualWrite(V0, PHaverage);
}

//=============================================================================================

int analogBuffer[SCOUNT]; // store the analog value in the array, read from ADC
int analogBufferTemp[SCOUNT];
int analogBufferIndex = 0,copyIndex = 0;
float averageVoltage = 0,tdsValue = 0,temperatureTDS = 25;

void sendTDS()
{
 static unsigned long analogSampleTimepoint = millis();
if(millis()-analogSampleTimepoint > 40U) //every 40 milliseconds,read the analog value from the ADC
{
analogSampleTimepoint = millis();
analogBuffer[analogBufferIndex] = analogRead(TdsSensorPin); //read the analog value and store into the buffer
analogBufferIndex++;
if(analogBufferIndex == SCOUNT)
analogBufferIndex = 0;
}
static unsigned long printTimepoint = millis();
if(millis()-printTimepoint > 800U)
{
printTimepoint = millis();
for(copyIndex=0;copyIndex<SCOUNT;copyIndex++)
analogBufferTemp[copyIndex]= analogBuffer[copyIndex];
averageVoltage = getMedianNum(analogBufferTemp,SCOUNT) * (float)VREF/ 1024.0; // read the analog value more stable by the median filtering algorithm, and convert to voltage value
float compensationCoefficient=1.0+0.02*(temperatureTDS-25.0); //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
float compensationVolatge=averageVoltage/compensationCoefficient; //temperature compensation
tdsValue=(133.42*compensationVolatge*compensationVolatge*compensationVolatge - 255.86*compensationVolatge*compensationVolatge + 857.39*compensationVolatge)*0.5; //convert voltage value to tds value
//Serial.print("voltage:");
//Serial.print(averageVoltage,2);
//Serial.print("V ");
Serial.print("TDS Value:");
Serial.print(tdsValue,0);
Serial.println("ppm");
Blynk.virtualWrite(V2, tdsValue);
}
}
int getMedianNum(int bArray[], int iFilterLen)
{
int bTab[iFilterLen];
for (byte i = 0; i<iFilterLen; i++)
bTab[i] = bArray[i];
int i, j, bTemp;
for (j = 0; j < iFilterLen - 1; j++)
{
for (i = 0; i < iFilterLen - j - 1; i++)
{
if (bTab[i] > bTab[i + 1])
{
bTemp = bTab[i];
bTab[i] = bTab[i + 1];
bTab[i + 1] = bTemp;
}
}
}
if ((iFilterLen & 1) > 0)
bTemp = bTab[(iFilterLen - 1) / 2];
else
bTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2;
return bTemp; 
}

//=============================================================================================

void sendWaterTemp()
{ 
  sensors.requestTemperatures(); 
  Celcius=sensors.getTempCByIndex(0);
  Fahrenheit=sensors.toFahrenheit(Celcius);
  Serial.print(" C  ");
  Serial.print(Celcius);
  Serial.print(" F  ");
  Serial.println(Fahrenheit);
  delay(1000);
  Blynk.virtualWrite(V16, Celcius);
  Blynk.virtualWrite(V17, Fahrenheit);
}

//=============================================================================================

void sendGravityPH()
{
    static unsigned long timepoint = millis();
    if(millis()-timepoint>1000U)  //time interval: 1s
    {
      timepoint = millis();
      voltage = analogRead(PH_PIN)/1024.0*5000;  // read the voltage
      //temperature = readTemperature();  // read your temperature sensor to execute temperature compensation
      phValue = ph.readPH(voltage,temperature);  // convert voltage to pH with temperature compensation
      Serial.print("temperature:");
      Serial.print(temperature,1);
      Serial.print("^C  pH:");
      Serial.println(phValue,2);
    }
    ph.calibration(voltage,temperature);  // calibration process by Serail CMD
}

float readTemperature()
{
  //add your code here to get the temperature from your temperature sensor
}

//=============================================================================================

void reconnectBlynk() {
  if (!Blynk.connected()) {

    Serial.println("Lost connection");
    if(Blynk.connect()) {
      Serial.println("Reconnected");
    }
    else {
      Serial.println("Not reconnected");
    }
  }
}

//=============================================================================================

void setup()
{
 
  Serial.begin(115200);

  
  Blynk.begin(auth);                       //Reguler server
  Blynk.syncAll();
  
  dht1.begin();
  dht2.begin();
  sensors.begin();
  ph.begin();
  
   pinMode(waterLevel_trigger, OUTPUT);
   pinMode(waterLevel_echo, INPUT);
   pinMode(hydroTrig, OUTPUT);
   pinMode(hydroEcho, INPUT);
   pinMode(TdsSensorPin,INPUT);
   pinMode(SDCARD_CS, OUTPUT);
   
  pinMode(22,OUTPUT); // 240v Output Pins
  pinMode(23,OUTPUT);
  pinMode(24,OUTPUT);
  pinMode(25,OUTPUT);
  pinMode(26,OUTPUT);
  pinMode(27,OUTPUT);
  pinMode(28,OUTPUT);
  pinMode(29,OUTPUT);
  pinMode(30,OUTPUT);
  pinMode(31,OUTPUT);
  pinMode(32,OUTPUT);
  pinMode(33,OUTPUT);
  pinMode(34,OUTPUT);
  pinMode(35,OUTPUT);
  pinMode(36,OUTPUT);
  pinMode(37,OUTPUT);
  pinMode(38,OUTPUT); // 12v Output Pins
  pinMode(39,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(41,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(43,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(45,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(47,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(49,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(51,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(53,OUTPUT);
  
  digitalWrite(22,HIGH); // 240v Relay Board
  digitalWrite(23,HIGH);
  digitalWrite(24,HIGH);
  digitalWrite(25,LOW);
  digitalWrite(26,LOW);
  digitalWrite(27,HIGH);
  digitalWrite(28,HIGH);
  digitalWrite(29,HIGH);
  digitalWrite(30,HIGH);
  digitalWrite(31,HIGH);
  digitalWrite(32,HIGH);
  digitalWrite(33,HIGH);
  digitalWrite(34,HIGH);
  digitalWrite(35,HIGH);
  digitalWrite(36,HIGH);
  digitalWrite(37,HIGH);
  digitalWrite(38,HIGH); // 12v Relay Board
  digitalWrite(39,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(41,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(43,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(45,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(47,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(49,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(51,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(53,HIGH);
  digitalWrite(SDCARD_CS, HIGH); // Deselect the SD card

 
  timer.setInterval(30*1000, reconnectBlynk);  
  
  timer.setInterval(2500L, sendDHT1Sensor);
  
  timer.setInterval(2000L, sendDHT2Sensor);
  
  timer.setInterval(5000L, sendWaterTemp);
  
  timer.setInterval(7500L, sendMoisture1);
  
  timer.setInterval(6500L, sendMoisture2);
  
  timer.setInterval(7000L, sendMoisture3);
  
  timer.setInterval(6000L, sendMoisture4);
  
  timer.setInterval(10000L, sendPhSensor);
  
  timer.setInterval(1080L, sendGravityPH);
  
  timer.setInterval(3000L, sendWaterlevel);
  
  timer.setInterval(2500L, sendTDS);
  delay(10);
    
 
 
}

void loop()
{
 timer.run(); 
  if(Blynk.connected()) { Blynk.run(); }
 
}
  1. Search forum for similar topics
  2. Check http://docs.blynk.cc and http://help.blynk.cc/
  3. Add details :
    • Hardware model + communication type. For example: Arduino UNO with Ethernet Shield
    • Smartphone OS (iOS or Android) + version
    • Blynk server or local server
    • Blynk Library version
    • Add your sketch code. :point_up:Code should be formatted as example below.

Simply paste your code between ``` If you don’t format your code, your topic can be deleted by moderators.


void loop()

Try the following construction

byte mac [ ] = { 0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED } ;
Ethernet.begin (mac);
Blynk.config(auth);
Blynk.connect();

Use a loop to reconnect.

void loop()
{
 timer.run(); 
  if(Blynk.connected()) { Blynk.run(); }else{
while (!Ethernet.begin (mac)){
Blynk.config(auth);
Blynk.connect();
}
}
 }

A useful rule of thumb is to get rid of all unnecessary delays like this one:

void sendWaterTemp()
{ 
  sensors.requestTemperatures(); 
  /.../
  delay(1000);
  /.../
}

The only thing it does is to bring everything else to a halt for 1 second, including your network, every 5th according to your timer:

timer.setInterval(5000L, sendWaterTemp);

But that’s not all, here comes the nasty part! :smiley:

If you are using a DS18B20 with the default 12-bit resolution (which it looks like), sensors.requestTemperatures() needs about 750 ms to return the temperature value. So all in all, every 5 seconds, your system halts for almost 2! And don’t even get me started on the DHT11 :nerd_face:

I would add a zero or more to your timers! I think you could manage without (near) real time temperature and humidity data :slight_smile:

1 Like

hi thanks for your reply I tried putting

byte mac [ ] = { 0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED } ;
Ethernet.begin (mac);
Blynk.config(auth);
Blynk.connect();

in the void set up and it comes back with (mac) wasnt declared
ive tried placing the code in different areas and still the same thing can you please elaborate a bit more on what you mean plase

thanks for your opinion it sounds like your familiar with the troubles of cheap sensors, whats your recommendation if you need real time temp and humidity and water temp sensors. I had a impression these sensors would be full of issues

For air conditions BME 280 is good. Make sure it’s BME not BMP. BMP doesn’t have humidity.

1 Like

MAC address must be written in Ethernet shield.

Do you really, really need the data that frequent? You’re not setting up a meth lab or something are you? :smiley: :wink:

As long as you use the DHT11 you’ll always have problems with the sampling rate. It’s old, cheep, slow and basically not built for high frequency sampling. And I’ve noticed that some libraries are slower than others because of built in delays.

But there is still hope for the DS18B20 sensor! :slight_smile: If you change the resolution from 12 to 9-bit (0.5 degree Celsius increments) the conversation time drops from ~750 ms to ~100 ms! Another approach to is to get creative with the setWaitForConversion() function. I managed to get the time spent for a 12-bit reading down to below 40 ms. Read the comments in my old project:

https://community.blynk.cc/t/cheap-est-rf-433-mhz-bridge-for-home-automation-with-both-tx-and-rx/

That would be a better sensor, especially for humidity.