/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#define timeSeconds 1000

// Set GPIOs for LED and PIR Motion Sensor
const int led = 26;
const int motionSensor = 27;
const float GAMMA = 0.7;
const float RL10 = 50;
// Timer: Auxiliary variables
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
boolean motion = false;

// Checks if motion was detected, sets LED HIGH and starts a timer
void IRAM_ATTR detectsMovement() {
  digitalWrite(led, HIGH);
  startTimer = true;  // Set startTimer to true whenever motion is detected
  lastTrigger = millis();
}


void setup() {
  Serial.begin(115200);
  pinMode(motionSensor, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, CHANGE);
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}


void loop() {
  int analogValue = analogRead(33);
  float voltage = analogValue / 1024. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
  Serial.println("LIGTH ",lux);

  
  now = millis();
  if((digitalRead(led) == HIGH) && (motion == false)) {
    Serial.println("MOTION DETECTED!!!");
    motion = true;
  }

  // Turn off the LED after the number of seconds defined in the timeSeconds variable
  if(startTimer && (now - lastTrigger > timeSeconds)) {
    Serial.println("Motion stopped...");
    digitalWrite(led, LOW);
    startTimer = false;
    motion = false;
    // Reattach interrupt
    attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, CHANGE);
  }
}