Code Recommendation - What can I improve from this code

So, I'm making a project on my own and I'm somewhat not satisfied of my own program, any suggestions that you can provide to improve my code?

#include <DHT.h>
#include <DHT_U.h>
#include "thingProperties.h"

#define DHTpin 13
#define DHTTYPE DHT11
#define pH_sensor_pin 35

int soil_sensor = 33;  // Define the analog pin for the soil moisture sensor
DHT dht(DHTpin, DHTTYPE);



float calibration_value = -107.45;
unsigned long int avgval;
int buffer_arr[10], temp;

void setup() {
  Serial.begin(9600);
  delay(1500);
  initProperties();
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
  dht.begin();
}

void loop() {
  ArduinoCloud.update();
  dht_sensor_getdata();
}

void dht_sensor_getdata() {
  // pH sensor reading
  pH = getPhValue();  // Update the pH variable for the cloud
  Serial.print("pH Value: ");
  Serial.println(pH);
  delay(1000);

  // Soil moisture sensor reading
  sm_sensor = analogRead(soil_sensor);  // Raw sensor value
  // Convert raw value to percentage
  delay(500);
  
  // DHT sensor readings
  float hm = dht.readHumidity();
  Serial.print("Humidity: ");
  Serial.println(hm);
  float temp = dht.readTemperature();
  Serial.print("Temperature: ");
  Serial.println(temp);
  humidity = hm;  // Update the humidity variable for the cloud
  temperature = temp;  // Update the temperature variable for the cloud
  delay(500);

  // Implementing the result function
  if (pH >= 5.5 && pH <= 6.8 && sm_sensor >= 2200 && sm_sensor <= 2457 && temperature >= 24 && temperature <= 26) {
    msg = "Eggplant is most applicable in this soil";
  } else if (pH >= 5.5 && pH <= 8.0 && sm_sensor >= 2300 && sm_sensor <= 2457 && temperature >= 23 && temperature <= 25) {
    msg = "Tomato is most applicable in this soil";
  } else if (pH >= 6.3 && pH <= 6.8 && sm_sensor >= 2900 && sm_sensor <= 3276 && temperature >= 28 && temperature <= 31) {
    msg = "Okra is most applicable in this soil";
  } else if (pH >= 6.4 && pH <= 6.6 && sm_sensor >= 2000 && sm_sensor <= 2500 && temperature >= 27 && temperature <= 28) {
   msg = "Pepper is most applicable in this soil";
  } else if (pH >= 6.0 && pH <= 6.7 && sm_sensor >= 2000 && sm_sensor <= 2457 && temperature >= 34 && temperature <= 36) {
   msg = "Ampalaya is most applicable in this soil";
  } else {
    msg = "No specific crop recommendation for these sensor values";
  }
  Serial.println(msg);
}

float getPhValue() {
  for (int i = 0; i < 10; i++) {
    buffer_arr[i] = analogRead(pH_sensor_pin);  // Reading pH sensor data
    delay(30);
  }

  // Sorting buffer_arr in ascending order
  for (int i = 0; i < 9; i++) {
    for (int j = i + 1; j < 10; j++) {
      if (buffer_arr[i] > buffer_arr[j]) {
        temp = buffer_arr[i];
        buffer_arr[i] = buffer_arr[j];
        buffer_arr[j] = temp;
      }
    }
  }

  // Calculating average of middle 6 values
  avgval = 0;
  for (int i = 2; i < 8; i++)
    avgval += buffer_arr[i];

  float volt = (float)avgval * 5.0 / 1023 / 6.0; // Corrected conversion
  float ph_act = 5.70 * volt + calibration_value;  // Corrected linear equation

  return ph_act;
}

void onMsgChange() {
  // Add your code here to act upon Msg change
}

void onPHChange() {
  // Add your code here to act upon PH change
}

void onHumidityChange() {
  // Add your code here to act upon Humidity change
}

void onTemperatureChange() {
  // Add your code here to act upon Temperature change
}

I'm just trying to improve my code and hoping to hear suggestions from experts

Still not clear on what you want. Does it not look pretty enough? Do you need to add more comments?
My suggestion is to begin the next project and make that code have the improvements you are looking for. If you change a working program, then you have to go through all the testing again!

3 Likes

This code can maybe be improved:

if (pH >= 5.5 && pH <= 6.8 && sm_sensor >= 2200 && sm_sensor <= 2457 && temperature >= 24 && temperature <= 26) {
    msg = "Eggplant is most applicable in this soil";
  } else if (pH >= 5.5 && pH <= 8.0 && sm_sensor >= 2300 && sm_sensor <= 2457 && temperature >= 23 && temperature <= 25) {
    msg = "Tomato is most applicable in this soil";
  } else if (pH >= 6.3 && pH <= 6.8 && sm_sensor >= 2900 && sm_sensor <= 3276 && temperature >= 28 && temperature <= 31) {
    msg = "Okra is most applicable in this soil";
  } else if (pH >= 6.4 && pH <= 6.6 && sm_sensor >= 2000 && sm_sensor <= 2500 && temperature >= 27 && temperature <= 28) {
   msg = "Pepper is most applicable in this soil";
  } else if (pH >= 6.0 && pH <= 6.7 && sm_sensor >= 2000 && sm_sensor <= 2457 && temperature >= 34 && temperature <= 36) {
   msg = "Ampalaya is most applicable in this soil";
  } else {
    msg = "No specific crop recommendation for these sensor values";
  }

Each if() tests whether the current sensor values are inside a range of pH, soil moisture and temperature in which a crop is applicable.

Do those ranges intersect? I think some of them do. So more than one crop could be applicable for the current sensor readings, and when that's true, I suspect the choice of "most applicable crop" is arbitrary.

To improve that, your code could test how close the current sensor readings are to the centroid of each range (using Pythagoras), and use that distance to determine the "most applicable" when more than one crop is applicable.

1 Like

look this over
this include a test function that demonstrates that more than 1 case in your multi-if statement may be true

ph   5.90, soil moist 2300, humidity  10.00, tempC  25.00 Eggplant Tomato
# include <DHT.h>
# include <DHT_U.h>
# include "thingProperties.h"

#define DHTpin 13
const byte PhSensorPin  = 35;
const byte SoilMoistPin = 33;

#define DHTTYPE DHT11
DHT dht (DHTpin, DHTTYPE);

float pH;
int   soilMoist;
float humidity;
float tempC;

char s [90];

// -----------------------------------------------------------------------------
struct Param {
    float pHmin;
    float pHmax;
    float soilMoistmin;
    float soilMoistmax;
    float tempCmin;
    float tempCmax;
    const char *msg;
}
params [] = {
    { 5.5, 6.8, 2200, 2457, 24, 26, " Eggplant"},
    { 5.5, 8.0, 2300, 2457, 23, 26, " Tomato"},
    { 6.3, 6.8, 2900, 3257, 28, 31, " Okra" },
    { 6.4, 6.6, 2000, 2500, 27, 28, " Pepper" },
    { 6.0, 6.7, 2000, 2457, 34, 36, " Ampalya" },
};
const int Nparams = sizeof (params)/sizeof(Param);

// -------------------------------------
void
eval ()
{
    Param *p = params;
    for (int n = 0; n < Nparams; n++, p++)  {
        if (p->pHmin <= pH && pH <= p->pHmax)  {
            if (p->soilMoistmin <= soilMoist && soilMoist <= p->soilMoistmax) {
                if (p->tempCmin <= tempC && tempC <= p->tempCmax)
                    Serial.print (p->msg);
            }
        }
    }
}

// -------------------------------------
void
disp ()
{
    char p[10];
    char h[10];
    char t[10];

    dtostrf (pH,       6, 2, p);
    dtostrf (humidity, 6, 2, h);
    dtostrf (tempC,    6, 2, t);

    sprintf (s, "ph %s, soil moist %4d, humidity %s, tempC %s",
            p, soilMoist, h, t);
    Serial.print (s);

    eval ();
    Serial.println ();
}

// -------------------------------------
void
test ()
{
    Serial.println ("------------- test -------------");
    for (pH = 5.3; pH <= 7.0; pH += 0.3)  {
        for (soilMoist = 2100; soilMoist <= 3400; soilMoist += 200)  {
            for (tempC = 23; tempC <= 38; tempC += 2)
                disp ();
        }
    }
    Serial.println ("--------------------------------");
}

// -----------------------------------------------------------------------------
float getPhValue () {
    const int Nsamp = 10;
    int sum;
    for (int i = 0; i < Nsamp; i++) {
        sum += analogRead (PhSensorPin);  // Reading pH sensor data
        delay (30);
    }
    const float PhCalibration = -107.45;

    float avg    = 1.0  *sum / Nsamp;
    float volt   = avg * 5.0 / 1023 / 6.0;     // Corrected conversion
    float ph_act = 5.70 * volt + PhCalibration;  // Corrected linear equation

    return ph_act;
}

// ---------------------------------
void dht_sensor_getdata () {
    pH        = getPhValue ();  
    soilMoist = analogRead (SoilMoistPin);
    humidity  = dht.readHumidity ();
    tempC     = dht.readTemperature ();

}

// -----------------------------------------------------------------------------
void loop () {
    if (Serial.available ())  {
        char c = Serial.read ();
        if ('+' == c)
            test ();
    }

    ArduinoCloud.update ();
    dht_sensor_getdata ();
    disp ();
}

// -----------------------------------------------------------------------------
void onMsgChange ()         { }
void onPHChange ()          { }
void onHumidityChange ()    { }
void onTemperatureChange () { }

// -----------------------------------------------------------------------------
void setup () {
    Serial.begin (9600);
    delay (1500);
 // initProperties ();
    ArduinoCloud.begin (ArduinoIoTPreferredConnection);
    setDebugMessageLevel (2);
    ArduinoCloud.printDebugInfo ();
    dht.begin ();
}
1 Like

I noticed that. And the series of complex if clauses seemed ripe for replacement and/or reorganization.

It would be good to remove the delay() calls, depending on how the sketch is expected to expand. Combine non-blocking reading of sensors with occasional timed printing...

getPhValue() could probably be optimized some, but doesn't need to be.
I like that it's quite obvious what you're doing...

@eardvyl - If your code works, leave it alone. As you write more programs, you will know how to "improve" upon this code.

(tomatoes)

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.