#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust the I2C address if needed
Servo servos[4];
const int servoPins[4] = {3, 5, 6, 9}; // Updated pins for servos
int moistureLevels[4];
int baseTime = 6000; // Base time for each servo in milliseconds
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.backlight();
// Attach servos to pins
for (int i = 0; i < 4; i++) {
servos[i].attach(servoPins[i]);
}
}
void loop() {
// Receive moisture levels from each C Arduino
for (int i = 0; i < 4; i++) {
if (Serial.available() > 0) {
moistureLevels[i] = Serial.read();
}
}
// Find min and max moisture levels
int minMoisture = moistureLevels[0];
int maxMoisture = moistureLevels[0];
for (int i = 1; i < 4; i++) {
if (moistureLevels[i] < minMoisture) minMoisture = moistureLevels[i];
if (moistureLevels[i] > maxMoisture) maxMoisture = moistureLevels[i];
}
// Calculate watering time and move each servo
int totalLoopTime = 0;
for (int i = 0; i < 4; i++) {
int moistureLevel = moistureLevels[i];
int additionalTime = map(moistureLevel, minMoisture, maxMoisture, 3000, 0); // Calculate based on dryness
int servoTime = baseTime + additionalTime;
// Move servo and display individual servo time on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Servo ");
lcd.print(i + 1);
lcd.print(" Time:");
lcd.setCursor(0, 1);
lcd.print(servoTime / 1000); // Display in seconds
lcd.print("s");
// Move servo to 90 degrees, wait, and return to 0
servos[i].write(90);
delay(servoTime);
servos[i].write(0);
// Add to total loop time
totalLoopTime += servoTime;
}
// Display total loop time on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Loop Time:");
lcd.setCursor(0, 1);
lcd.print(totalLoopTime / 1000); // Display total time in seconds
delay(2000); // Delay before the next loop
}