#include <Stepper.h>

#define ECHO_PIN A0
#define TRIG_PIN A1
#define LDR_PIN A2
#define LED_PIN 12

// Constant for the LDR  photoresistor
const float GAMMA = 0.7;
const float RL10 = 50;

const int stepsPerRevolution = 200;
Stepper motor(stepsPerRevolution, 8, 9, 10, 11);

// Thresholds for the curtains (in lux)
bool isOpen = false;


// Reads the distance in cm from the ultrasonic sensor
float readDistance() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  return duration * 0.034 / 2;
}

void setup() {
  Serial.begin(115200);
  pinMode(ECHO_PIN, INPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(LDR_PIN, INPUT);
  // LED ON = curtains open
  pinMode(LED_PIN, OUTPUT);
  motor.setSpeed(60);
}

void loop() {
  float distance = readDistance();
  int lightLevel = analogRead(LDR_PIN);

  float voltage = lightLevel / 1024. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  Serial.print("Measured distance in front of the sensor: ");
  Serial.print(readDistance());
  Serial.println(" cm");

  Serial.print("Current light level is: ");
  Serial.print(lux);
  Serial.println(" lux");


  if(distance < 100) {
    Serial.println("User detected in front of the sensor");
    Serial.println();

    // Room is too dark, open the curtains
    if(lux < 100) {
      if(!isOpen) {
        Serial.println("The room is too dark, opening the curtains...");
        motor.step(stepsPerRevolution);
        isOpen = true;
      }
      else {
        Serial.println("Curtains already open");
      }
    } 
    // Room is a bit bright, close the curtains a bit
    else if(lux >= 500 && lux < 1500){
      if(isOpen) {
        Serial.println("The room is bright, closing the curtains a bit...");
        motor.step(-stepsPerRevolution / 2);
      }
      else {
        Serial.println("Curtains already closed");
      }
    }
    // Room is too bright, close the curtains
    else if(lux >= 2000){
      if(isOpen) {
        Serial.println("The room is too bright, closing the curtains");
        motor.step(-stepsPerRevolution);
        isOpen = false;
      }
      else {
        Serial.println("Curtains already closed");
      }
    }
  }

  delay(5000);
}


uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND
ldr1:VCC
ldr1:GND
ldr1:DO
ldr1:AO
stepper1:A-
stepper1:A+
stepper1:B+
stepper1:B-