#include <Stepper.h>
const int stepsPerRevolution = 2048;
Stepper myStepper(stepsPerRevolution, 8, 11, 10, 12);
const int waterSensorPin = A1;
const int threshold = 300;
bool lastWetState = false; // remembers previous state
void setup() {
Serial.begin(9600);
Serial.println("Stepper motor water direction demo starting...");
myStepper.setSpeed(10); // RPM
}
void loop() {
int sensorValue = analogRead(waterSensorPin);
bool isWet = sensorValue > threshold;
Serial.print("Water sensor value: ");
Serial.println(sensorValue);
// ✅ Detect state change
if (isWet != lastWetState) {
unsigned long startTime = millis();
if (isWet) {
Serial.println("Wet detected → Clockwise for 5 seconds");
while (millis() - startTime < 5000) {
myStepper.step(1); // clockwise
}
} else {
Serial.println("Dry detected → Counterclockwise for 5 seconds");
while (millis() - startTime < 5000) {
myStepper.step(-1); // counterclockwise
}
}
Serial.println("Motor stopped.\n");
// ✅ Update last state AFTER motor action
lastWetState = isWet;
}
delay(200); // small delay to reduce sensor noise
}