#include <Servo.h>
#define NOTE_A4  440

const int motorPin = 11;
const int trigPin = 10;
const int echoPin = 9;
const int lightPinBack = A2; // Photocell behind memo
const int lightPinBelow = A5; // Photocell below book
const int buzzerPin = 2; 

Servo myMemoArm;

// change depends on env 
int lightThresholdBack = 750; // memo want dark
int lightThresholdBelow = 600;// book want dark

float distance;
unsigned long lastFlipTime = 0; //cool down: prevent triggering memo removal

unsigned long minFlipTime = 0; //minimum flip time: prevent triggering from other hand movement

float readDistanceCM() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  


unsigned long t = pulseIn(echoPin, HIGH, 30000);
  if (t == 0) return -1;
  return t * 0.0343f / 2.0f; //distance = time × speed of sound


}

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  pinMode(lightPinBack, INPUT);
  pinMode(lightPinBelow, INPUT);
  
  pinMode(buzzerPin, OUTPUT); 
  
  myMemoArm.attach(motorPin);
  myMemoArm.write(0);
}

void loop() {
  distance = readDistanceCM();
  int lightValueBack  = analogRead(lightPinBack);
  int lightValueBelow = analogRead(lightPinBelow);

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.print(" cm | Memo Back: ");
  Serial.print(lightValueBack);
  Serial.print(" | Below Book: ");
  Serial.println(lightValueBelow);
  
//  ------ Book removal
// condition: photocell at the back of the book detect higher light
if (lightValueBelow > lightThresholdBelow) {
  Serial.println("Detect Book Removal");
  myMemoArm.write(0);
  tone(buzzerPin, 440, 300);
  delay(250);
  noTone(buzzerPin);
}

// ------ Page flip
// condition: stay in distance range (20-25cm) for more than 1000ms
  else if (distance > 20 && distance < 25) {
    if (minFlipTime == 0) {
    minFlipTime = millis(); // start counting only once when entering range
    }

    if (millis() - minFlipTime > 500) {
      Serial.println("Detect Page Flip, Memo Flip");
      myMemoArm.write(90);
      delay(800); // cool down
      lastFlipTime = millis(); // prevent triggering memo removal
      minFlipTime = 0;         // reset so it won't retrigger Page Flip immediately
    }
  }


// ------ Memo removal
//condition: photocell at the back of the memo detect higher light
else if ( millis() - lastFlipTime > 2000 && lightValueBack > lightThresholdBack) {
  Serial.println("Detect Memo Removel");
  delay(1000);

  for (int i = 0; i < 3; i++) {
    myMemoArm.write(60);
    delay(100);
    myMemoArm.write(0);
    delay(100);
    tone(buzzerPin, 880, 100);
    delay(200);
  }
  noTone(buzzerPin);
}

// ------ Idle behavior
else {
myMemoArm.write(0);
}

delay(100);
  }