I am building a very simple sprinkler controller to water my wife’s herb garden. She is going to be planting them in window sill type flower boxes. I plan on using a moisture sensor to determine the soil moisture and turn on the water flow for a specified time. The sketch below performs fine on the breadboard though I still have to tweak the values of MoistureLevel and SprinkleDuration once the boxes are finished and herbs are planted. While this sketch should do great for one box I’d like to expand this code to control more boxes. Of course there are countless ways to totally rewrite this sketch but I’m trying to learn a little something along the way as well. That said, I don’t think in loops very well and would like come help converting this code to use both “arrays” and “for” loops to monitor 6 boxes (A0-A5) and control their corresponding valves (pin 2-7). I only want one box monitored and watered at a time so the code needs to be “blocking” so that each box is checked and watered before moving on to the next one. Any ideas?
/*
Sprinkler Controller
Ground moisture sensor turns on sprinkler for a specified time if the sensor
indicates that the ground moisture drops below a specified level.
*/
// Variable definitions
#define MoistureLevel 512 // minimum soil moisture level
#define MoistureValue 0 // soil moisture value from the soil moisture sensor
#define SprinkleDuration 5 // time sprinkler will stay on
// Pin assignments
#define MoisturePin A0 // pin the moisture sensor inputs to
#define SprinklePin 2 // pin the sprinkler relay is controlled by
/* Rename variables according to their function
PIN... = Pin assignments
LEVEL... = Pre-defined (or calibrated) level
VALUE... = Value obtained from an input
TIME... = A value corresponding to a time measurement
*/
int PINmoisture = MoisturePin;
int PINsprinkle = SprinklePin;
int LEVELmoisture = MoistureLevel;
int VALUEmoisture = MoistureValue; // variable to store the value from the moisture sensor
int TIMEsprinkle = SprinkleDuration; // time sprinkler will stay on after turning on
void setup() {
pinMode(PINsprinkle, OUTPUT); // declare the PINsprinkle as an OUTPUT
TIMEsprinkle = TIMEsprinkle * 1000; // Time in seconds for testing
// TIMEsprinkle = TIMEsprinkle * 60000; // Time in minutes
}
void loop() {
digitalWrite(PINsprinkle, LOW); // Preset sprinkler relay off
VALUEmoisture = analogRead(PINmoisture);// Read soil moisture
delay(150); // debounce delay
while (VALUEmoisture < LEVELmoisture){ // do this while soil moisture is below level
digitalWrite(PINsprinkle, HIGH); // turn on sprinkler valve
delay(TIMEsprinkle); // leave it on for this long and wait until finished
break; // exit and allow sensor to recheck the moisture
}
}