I am writing software that reads soil moisture levels and checks every hour (right now it's set to every minute) if it's below a certain percentage. If it is, it initiates a function that turns on a water pump for 5 seconds. Outside of checking, it also changes an RGB LED from red to green (more water = more green) after reading the moisture level. I have 2 plants and therefore am using 2 RGB LEDs and a servo to aim the water at each plant.
I am having issues with initiating the watering function waterPlant(). Whenever the program gets to it, it seems to break the whole program (motor doesn't turn on, waterLED doesn't turn off, RGB LEDs freeze, etc). I tried giving enough delay time throughout the function but it still breaks.
Code:
#include <Servo.h>
Servo servo;
const int servoPin = 8;
const int base = 90;
const int plant1 = 170;
const int plant2 = 10;
const int wet1 = 288;
const int dry1 = 640;
const int wet2 = 310;
const int dry2 = 633;
const int wet1o = 288;
const int dry1o = 629;
const int wet2o = 302;
const int dry2o = 620;
int soil_1, soil_2;
const int redPin1 = 6;
const int greenPin1 = 11;
const int redPin2 = 3;
const int greenPin2 = 5;
const int waterLED = 4;
const int servDelay = 1250;
const int waterDelay = 5000;
const int pump1 = 12;
unsigned long curTime;
unsigned long checkDelay = 60000; //Check water concentration every hour
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(pump1, OUTPUT);
servo.attach(servoPin);
servo.write(base);
pinMode(redPin1, OUTPUT);
pinMode(greenPin1, OUTPUT);
pinMode(redPin2, OUTPUT);
pinMode(greenPin2, OUTPUT);
pinMode(waterLED, OUTPUT);
curTime = millis();
}
void loop() {
// put your main code here, to run repeatedly:
soil_1 = abs(map(analogRead(A0), dry1, wet1, 0, 100));
soil_2 = abs(map(analogRead(A1), dry2, wet2, 0, 100));
if (digitalRead(pump1) == LOW) {
soil_1 = abs(soil_1 - 3);
soil_2 = abs(soil_2 - 4);
}
onLED(soil_1, redPin1, greenPin1);
onLED(soil_2, redPin2, greenPin2);
// Serial.println(soil_1);
// Serial.println(soil_2);
// Serial.println(" ");
delay(100);
Serial.println(millis()); // Debugging line
if (millis() - curTime >= checkDelay) {
if (soil_1 < 60) {
waterPlant(plant1);
}
delay(5000);
if (soil_2 < 60) {
waterPlant(plant2);
}
curTime = millis();
}
}
void onLED(int perc, int rp, int gp) {
// Changes RGB LED based on moisture reading
analogWrite(rp, 100 - perc);
analogWrite(gp, perc);
}
void waterPlant(int aim) {
// Waters a specific plant
digitalWrite(waterLED, HIGH);
servo.write(aim);
delay(servDelay);
digitalWrite(pump1, HIGH);
delay(waterDelay);
digitalWrite(pump1, LOW);
servo.write(base);
delay(servDelay);
digitalWrite(waterLED, LOW);
}