const int moisturePin = A1; // Pin connected to the soil moisture sensor
const int relayPin = 7; // Pin connected to the relay
// Define calibration values
const int dryValue = 700; // Analog reading when sensor is dry
const int wetValue = 300; // Analog reading when sensor is wet
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(moisturePin, INPUT);
pinMode(relayPin, OUTPUT);
}
void loop() {
// Read soil moisture
int moisture = analogRead(moisturePin);
// Convert analog reading to moisture percentage using calibration values
int moisturePercentage = map(moisture, dryValue, wetValue, 0, 100);
// Print moisture value to serial monitor
Serial.print("Moisture Percentage: ");
Serial.println(moisturePercentage);
// Check if soil moisture exceeds wet threshold
if (moisture <= wetValue) {
// If moisture is below wet threshold, turn on relay
digitalWrite(relayPin, HIGH);
Serial.println("Soil moisture is high. Turning relay on.");
} else {
// Otherwise, turn off relay
digitalWrite(relayPin, LOW);
Serial.println("Soil moisture is low. Turning relay off.");
}
// Delay for stability
delay(1000);
}
The relay keeps activating even when the sensor isnt connected and the monitor is giving random values. Whats wrong?
