#include <Servo.h>
const int DIST_THRESHOLD = 20;
const int MOIST_THRESHOLD = 40;
const int TRIG_PIN = 12;
const int ECHO_PIN = 11;
const int SERVO_PIN = 2;
const int SENSOR_PIN = A0;
int oldDistance = 0;
int oldMoisture = 0;
Servo servo;
int getDistance() {
// send trigger
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// calculate distance
unsigned long duration = pulseIn(ECHO_PIN, HIGH);
float distance = (duration * .0343) / 2;
// return distance as an integer
return (int)(distance + 0.5);
}
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
servo.attach(SERVO_PIN);
servo.write(90);
}
void loop() {
int distance = getDistance();
int senseVal = analogRead(SENSOR_PIN);
int moisture = map(senseVal, 0, 1023, 0, 100);
// prints distance if it changes by 3 or more cm
if ((distance) > (oldDistance + 3) || (distance) < (oldDistance - 3)) {
oldDistance = distance;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
// prints moisture percentage if it changes
if (moisture != oldMoisture) {
oldMoisture = moisture;
Serial.print("Moisture: ");
Serial.print(moisture);
Serial.println("%");
}
if (distance < DIST_THRESHOLD) { // only if an object is close
if (moisture <= MOIST_THRESHOLD) { // then check if it's wet or dry
servo.write(180); // dry
} else {
servo.write(0); // wet
}
} else { // not close
servo.write(90);
}
}
Wet
Wet
Dry
Dry