Document (22)
Document (22)
the LCD, we can modify it to calculate and show the moisture level as a
percentage. Here's the updated code: ```cpp #include // Initialize the LCD
(rs, en, d4, d5, d6, d7) LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Pin definitions
const int moistureSensorPin = A0; // Soil moisture sensor pin const int
pumpPin = 9; // Water pump pin // Threshold for wet soil const int
moistureThreshold = 600; // Adjust this value based on your sensor void
setup() { lcd.begin(16, 2); // Set up the LCD’s number of columns and rows
pinMode(pumpPin, OUTPUT); // Set the pump pin as an output
digitalWrite(pumpPin, LOW); // Ensure the pump is off initially lcd.print(“Plant
Watering Sys”); // Display initial message delay(2000); // Wait for 2 seconds
lcd.clear(); // Clear the display } void loop() { int moistureLevel =
analogRead(moistureSensorPin); // Read the moisture level int
moisturePercentage = map(moistureLevel, 0, 1023, 100, 0); // Map to
percentage lcd.setCursor(0, 0); // Set cursor to the first line if (moistureLevel
< moistureThreshold) { lcd.print(“Soil: Dry “); // Display dry message
waterPlant(); // Water the plant } else { lcd.print(“Soil: Wet “); // Display wet
message } lcd.setCursor(0, 1); // Set cursor to the second line
lcd.print(“Moisture: “); // Display moisture label
lcd.print(moisturePercentage); // Display moisture percentage lcd.print(“% “);
// Print percentage with padding delay(2000); // Wait for 2 seconds before the
next reading } void waterPlant() { lcd.setCursor(0, 1); // Set cursor to the
second line lcd.print(“Watering… “); // Display watering message
digitalWrite(pumpPin, HIGH); // Turn on the pump delay(5000); // Water for 5
seconds (adjust as needed) digitalWrite(pumpPin, LOW); // Turn off the pump
lcd.setCursor(0, 1); // Set cursor to the second line lcd.print(“Done watering
“); // Indicate done watering } ``` In this updated code, the
`moisturePercentage` variable calculates the moisture level as a percentage
by mapping the analog reading (0 to 1023) to a percentage scale (100% to
0%). The LCD then displays this percentage on the second line, along with a
label for clarity. The moisture value is refreshed every 2 seconds, along with
the watering status.