Following is an example how it could be coded.
Remember that the soil is dry by setting DrySoil = true
.
Register the time at which a dry period starts in DrySoilBegin.
Check at each 'dry' reading whether DrySoil was true for more than 20 minutes.
Set DrySoil = false
at every 'not dry' reading.
The ul
after the constant 1200000
makes it an unsigned long value. This because millis()
returns a unsigned long
result. I am not 100% sure this is necessary (maybe the compiler takes care of this automatically).
As I don't have a plant watering system I couldn't verify the proper working..
#define WATERPIN 10
#define READSOILPIN A0
#define LEDPIN 13
// higher number is more dry
#define MAXDRYNESS 700
#define WATERDELAY 10000
#define WATERPOSTDELAY 5000
bool DrySoil = false; // State of soil
unsigned long DrySoilBegin; // Time when DrySoil became true
void setup() {
Serial.begin(9600);
pinMode(READSOILPIN, INPUT);
pinMode(WATERPIN, OUTPUT);
pinMode(LEDPIN, OUTPUT);
}
void loop() {
int SensorValue = analogRead(READSOILPIN); //take a sample
Serial.print(SensorValue);
Serial.print(" ־ ");
if(SensorValue >= MAXDRYNESS) {
// Soil is too dry
// Check if soil was already in a dry state
if(DrySoil){
// If already in a dry state check the duration
if((millis()-DrySoilBegin) > 1200000ul){
// If duration is longer than 20 minutes switch LED on
// or keep LED switched on
digitalWrite(LEDPIN, HIGH);
}
}
else{
// First 'dry' result after 'wet' result(s)
DrySoil = true; // Set DrySoil in true state
DrySoilBegin = millis(); // Set beginning of DrySoil period
}
// start watering for 10 seconds then
// wait for 5 seconds before monitoring again
Serial.println("Soil dry start watering");
digitalWrite(WATERPIN, HIGH);
delay(WATERDELAY); // wait until WATERDELAY milliseconds have passed
digitalWrite(WATERPIN, LOW);
delay(WATERPOSTDELAY); // wait until WATERPOSTDELAY milliseconds have passed
}
else{
// Soil is not too dry
DrySoil = false; // Set or keep DrySoil in state false
digitalWrite(LEDPIN, LOW); // Switch LED off, or keep it switched off
delay(50); // Wait 50 ms before next sampling
}
}
delay()
calls and learn the non-blocking coding style from theBlinkWithoutDelay
example. It uses themillis()
function, that returns the milliseconds since startup. You can use this as a clock to time the 20min. The coding style has been explained many times on the web.code
block, this will allow us to insert the lines of code you are looking for.