Sensors giving faulty readings

Hi I was hoping I could get advice with my code im finding the readings from my sensors are playing up. At the moment im not getting any reading from my ultrasonic sensor, can you please have a look at my code and tell me how to impove it.



#define BLYNK_PRINT Serial

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

#define W5100_CS  10
#define SDCARD_CS 4


char auth[] = "hJRROFHZaD0zxMx7GaqZBCIRDMr52Amf";


#define waterLevel_trigger 3      // Water level sensor
#define waterLevel_echo 4
#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 Diameter = 40;
const int Depth = 56;
const int Diameter2 = 40;
const int Depth2 = 56;
const int Area = PI * ((Diameter / 2) * (Diameter / 2));


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

  if (distance >= Depth || distance == 0 ) distance = Depth;

   WaterDepth = Depth - distance;
   Litres = (Area * WaterDepth) / 1000;
 
  Serial.print(distance);
  Serial.println("Centimeter");
  Serial.println("Tank 1 water depth: " + String(WaterDepth));     //print depth
  Blynk.virtualWrite(V1, WaterDepth);
  Serial.println("Tank 1 Litres: " + String(Litres));                         //print litres
  Blynk.virtualWrite(V8, Litres);

  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 || distance == 0 ) distance2 = Depth2;

   WaterDepth2 = Depth2 - distance2;
   Litres2 = (Area * WaterDepth2) / 1000;
 
  Serial.print(distance2);
  Serial.println("Centimeter");
  Serial.println("Tank 1 water depth: " + String(WaterDepth2));     //print depth
  Blynk.virtualWrite(V12, WaterDepth2);
  Serial.println("Tank 1 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 send
DHT2Sensor()
{
  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(1000L, sendDHT1Sensor);
  
  timer.setInterval(1000L, sendDHT2Sensor);
  
  timer.setInterval(1000L, sendWaterTemp);
  
  timer.setInterval(1000L, sendMoisture1);
  
  timer.setInterval(1000L, sendMoisture2);
  
  timer.setInterval(1000L, sendMoisture3);
  
  timer.setInterval(1000L, sendMoisture4);
  
  timer.setInterval(6000L, sendPhSensor);
  
  timer.setInterval(1000L, sendGravityPH);
  
  timer.setInterval(1000L, sendWaterlevel);
  
  timer.setInterval(1000L, sendHydroLevel);
  
  timer.setInterval(1000L, sendTDS);
  delay(10);
    
 for (int i = 0; i < 3; i++);  
 
}

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

sorry my request was very blunt. Im having trouble combining multiple sensors and getting them to give me accurate readings, Im finding they jump around a bit. if I run one ultrasonic sensor it works perfectly but when I add another its seems to give me nothing. Im trying to follow similar pattern in code but not sure if Im doing it correctly please help point me in the right direction.
thanks

I’d start by only using GPIO4 for one thing!

I’d also stagger you timers so that they aren’t all being called at precisely the same time, once every second, and read your DHT sensors no more than once every 5 seconds.

I have no idea why you have this at the end of your void setup, but it doesn’t achieve anything.

Pete.

thanks Pete
I have no idea what this is either it has something to do with the Ph sensor, I kept it there because it worked and I didnt want to disrupt it, ill try what you said

for (int i = 0; i < 3; i++);

Hi Pete
ive made some changes and there are some improvements but my main concern at the moment is the 2 ultrasonic sensors, one works fine but the other works great until the tank is half full then starts giving readings in the minus and I dont understand why or how to change it.

I want it to read normally as the tank fills.
have a look at the code and tell me if im missing something because im lost on why this is happening



#define BLYNK_PRINT Serial

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

#define W5100_CS  10
#define SDCARD_CS 4


char auth[] = "hJRROFHZaD0zxMx7GaqZBCIRDMr52Amf";


#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 Diameter = 40;
const int Depth = 56;
const int Diameter2 = 28;
const int Depth2 = 26;
const int Area = PI * ((Diameter / 2) * (Diameter / 2));


int Litres, Litres2, distance, distance2, WaterDepth, WaterDepth2;
    
void sendWaterlevel()
{
 long duration, distance, distance2;
  digitalWrite(waterLevel_trigger, LOW);  
  delayMicroseconds(2); 
  
  digitalWrite(waterLevel_trigger, HIGH);
  delayMicroseconds(10); 

  digitalWrite(hydroTrig, LOW);  
  delayMicroseconds(2); 

   digitalWrite(hydroTrig, HIGH);
  delayMicroseconds(10); 
  
  digitalWrite(waterLevel_trigger, LOW);
  duration = pulseIn(waterLevel_echo, HIGH);
  distance = (duration/2) / 29.1;

  digitalWrite(hydroTrig, LOW);
  duration = pulseIn(hydroEcho, HIGH);
  distance2 = (duration/2) / 29.1;
   if (distance >= Depth || distance == 0 ) distance = Depth; 
   if (distance2 >= Depth2 || distance == 0 ) distance2 = Depth2;

   WaterDepth = Depth - distance;
   Litres = (Area * WaterDepth) / 1000;

   WaterDepth2 = Depth2 - distance2;
   Litres2 = (Area * WaterDepth2 * 1.5) / 1000;
 
  Serial.print(distance);
  Serial.print(distance2);
  Serial.println("Centimeter");
  Serial.println("Tank 1 water depth: " + String(WaterDepth));     //print depth
  Serial.println("Hydro water depth: " + String(WaterDepth2));     //print depth
  Blynk.virtualWrite(V1, WaterDepth);
  Blynk.virtualWrite(V12, WaterDepth2 * 2);
  Serial.println("Tank 1 Litres: " + String(Litres));                         //print litres
  Serial.println("Hydro Litres: " + String(Litres2));                         //print litres
  Blynk.virtualWrite(V8, 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(); }
 
}

I’ve deleted your other topic where you posted exactly the same info.
Please keep the discussion in one place, otherwise it gets very messy.

It would help if you were more specific. Which senso4 works fine all the time, and which one doesn’t?

Pete.

Sorry so the ultrasonic sensor measuring the water level tank works but it is also connected to a calculation to tell me how many litres are in the tank it all works correctly and measures up to 32 litres (half tank) then it begins to show a minus symbol and continues to calculate back down till it hits 0. Its meant to go up to 50 litres.
The hydro tank sensor works correctly from 0 to it hits 20 litres, I was hoping the pictures help understand my problem
Thanks

Not really, as they don’t show which virtual pins the widgets are attached to, so trying to link the code to the pictures is guesswork.

I don’t understand why, if your tasks are different diameters, you can have just one calculation for area.

Also, some of the code is wrong…

I think this should be distance2

I think your code wold be easier to follow, and easier to spot mistakes such as this, if you arranged it differently.
Take the readings from one sensor, do the calculations and send it to Blynk and the serial monitor, then do the same for the second sensor rather than chopping and changing between sensors.

Pete.

1 Like