#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);
}