Analog read timing

I'm trying to set up a simple water (or lack thereof) detector using 2 stainless steel ping and analog input on an esp32 in a hydroponic water tube. I want to turn on a relay to send power to one of the pins, obtain a reading, and turn off the relay. I found by leaving power on one of he pins full time, it will corrode with the salts, and give false readings. The issue i am having, is the code I am trying takes about 8 or more cycles for the readings to stabilize. The code below is pnly cycling every 6 seconds, but I do want to only take a reading every 10 minutes. Any suggestion would be welcome


// Define analog input
#define inputPin 4
#define relay 23

int relayState = LOW;

int waterPct = 0;
const int numReadings = 4;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
unsigned long currentTime = 0;
unsigned long previousMillis = 0;
const unsigned long intervals[] = {2000, 5000}; //the two intervals



void readPin() {
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = 5*(total / numReadings);
  // send it to the computer as ASCII digits
  delay(10);        // delay in between reads for stability
}


void printAve() {
  if (currentTime - previousMillis >= intervals[relayState]) {
    previousMillis = currentTime;
    if (relayState == LOW) {
      relayState = HIGH;
    } else {
      relayState = LOW;
      readPin();
    }
    digitalWrite(relay, relayState);
    Serial.print("average "); Serial.println(average);

  }
}
void setup() {
  Serial.begin(115200);
  pinMode(relay, OUTPUT);
  pinMode(inputPin, INPUT);
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
  digitalWrite(relay, HIGH);
}

void loop() {
  printAve();
  currentTime = millis();
}

  • Try carbon electrodes, power to electrodes can easily controlled by a relay.

  • Capacitive Soil Moisture Sensors are a better option.

1 Like

I think the same issue will appear; having to wait for 8 cycles for the average to stabilize.
I will have to use the stainless powered continuously until I get some soil sensors in.

If the readings do not change, the average will take 3 cycles to stabilize. If there is a change in the readings it will take longer to stabilize.

You can try printing the whole array and check what is going on.