Functii:
Laburi folosite:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
int moist = A0;
char data = 0;
char prevData = 0;
const int RELAY_PIN = 3;
LiquidCrystal_I2C lcd(0x27, 16, 2);
String previousStatus = ""; // To store the previous status
unsigned long previousMillis = 0; // To store the last time the sensor was read
const long interval = 3000; // Interval for reading the sensor (3 seconds)
bool manualMode = false; // To track whether we are in manual mode
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
lcd.init(); // initialize the lcd
lcd.backlight();
pinMode(RELAY_PIN, OUTPUT);
}
// Function to create a string of fixed length
String createFixedLengthString(String message, int length) {
int messageLength = message.length();
while (messageLength < length) {
message += " "; // Add a space to pad the message
messageLength++;
}
return message;
}
void updateLCD(String status) {
// Pad the status message to the width of the LCD
status = createFixedLengthString(status, 16); //16 char for the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Moist Type: ");
lcd.setCursor(0, 1);
lcd.print(status);
}
void readSensorAndUpdateLCD() {
int moist_val = analogRead(moist);
String status;
if ((moist_val >= 600) && (moist_val <= 1200)) {
status = "Dry";
digitalWrite(RELAY_PIN, HIGH);
} else if ((moist_val >= 370) && (moist_val < 600)) {
status = "Humid";
digitalWrite(RELAY_PIN, LOW);
} else if (moist_val <= 370) {
status = "Wet";
digitalWrite(RELAY_PIN, LOW);
}
// Only update the LCD and print to Serial if the status has changed
if (status != previousStatus) {
Serial.println(status + " Soil");
updateLCD(status);
previousStatus = status; // Update the previous status
}
}
void loop() {
unsigned long currentMillis = millis();
// Check if it's time to read the sensor
if (currentMillis - previousMillis >= interval && !manualMode) {
previousMillis = currentMillis;
readSensorAndUpdateLCD();
}
// Check for manual control commands
if (Serial.available() > 0) {
data = Serial.read();
if (data != prevData) {
if (data == '1') {
manualMode = true; // Enable manual mode
digitalWrite(RELAY_PIN, HIGH);
updateLCD("Manual On");
} else if (data == '0') {
manualMode = true; // Enable manual mode
digitalWrite(RELAY_PIN, LOW);
updateLCD("Manual Off");
} else if (data == 'a') {
manualMode = false; // Return to automatic mode
readSensorAndUpdateLCD(); // Immediately read sensor and update LCD
}
prevData = data; // Update the previous data
}
}
}