/*
  Wet / Dry Waste Bin
  From an idea by https://www.youtube.com/watch?v=qFOtiU0P3Ys&t=157s
  If an object comes within DIST_THRESHOLD its moisture is sensed.
  Depending on that reading the servo opens one side of the bin or the other.
*/
#include <Servo.h>
// user settings
const int DIST_THRESHOLD = 15;  // distance threshold (cm)
const int DRY_THRESHOLD = 30;   // moisture threshold (%)
// pin constants
const int TRIG_PIN = 12;
const int ECHO_PIN = 11;
const int SERVO_PIN = 8;
const int SENSE_PIN = A0;
Servo flapServo;
int getDistance()  {
  // create trigger pulse
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  // measure the duration of the pulse on the echo pin
  long pulseLen = pulseIn(ECHO_PIN, HIGH);
  // calculate the distance, convert to int and round up
  int dist = (int) (pulseLen * 0.0343 / 2) + 0.5;
  return dist;
}
int getMoisture() {
  int rawSense = analogRead(SENSE_PIN);
  int senseValue = constrain(rawSense, 485, 1023);
  int moistValue = map(senseValue, 485, 1023, 100, 0);
  return moistValue;
}
void updateDisplay(int dist, int moist)  {
  Serial.print("Distance: ");
  Serial.print(dist);
  Serial.print(" cm, ");
  Serial.print("Humidity: ");
  Serial.print(moist);
  Serial.print("%\t");
}
void moveServo(bool isDry)  {
  if (isDry) {
    flapServo.write(135);
    delay(2000);
    flapServo.write(90);
  } else {  // is wet ofc...
    flapServo.write(45);
    delay(2000);
    flapServo.write(90);
  }
}
void setup()  {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  flapServo.attach(SERVO_PIN);
  Serial.println("Wet / Dry Waste Bin\n");
}
void loop() {
  int distance = getDistance();
  if (distance <= DIST_THRESHOLD) {
    int moistVal = getMoisture();
    updateDisplay(distance, moistVal);
    if (moistVal > DRY_THRESHOLD) {
      Serial.println(" ==>WET Waste ");
      moveServo(true);
    } else {
      Serial.println(" <==DRY Waste ");
      moveServo(false);
    }
  } else {
    flapServo.write(90);  // 90 for 180° servo
  }
  delay(1000);  // wait 1 second between readings
}