#include <Servo.h>
typedef Servo Screen;
// rgb led pins
const int RED_PIN = 11,
GREEN_PIN = 10,
BLUE_PIN = 9;
// servo objects pins
const int SERVO1_PIN = 3,
SERVO2_PIN = 5,
SERVO3_PIN = 6;
// servo angles
const int OPEN_ANGLE = 90,
CLOSE_ANGLE = 0;
// ldr
const int LDR_PIN = A0,
MAX_LDR_VALUE = 1015, // wokwi value
MIN_LDR_VALUE = 8; // wokwi value
int previousLuminosityPercent = -1, luminosityPercent;
// to the delay function...
const int ONE_SECOND = 1000;
// the servomotors objects
Screen screens[3];
// to moveScreens function
int screensToClose = 0;
// functions...
void rgb(bool r, bool g, bool b);
void turnRed();
void turnYellow();
void turnGreen();
void openScreen(Screen screen);
void closeScreen(Screen screen);
int getLuminosityPercent();
int moveScreens();
void setup() {
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
rgb(0, 0, 0);
pinMode(LDR_PIN, INPUT);
screens[0].attach(SERVO1_PIN);
screens[0].write(0);
screens[1].attach(SERVO2_PIN);
screens[1].write(0);
screens[2].attach(SERVO3_PIN);
screens[2].write(0);
Serial.begin(9600);
}
void loop() {
luminosityPercent = getLuminosityPercent();
if (luminosityPercent != previousLuminosityPercent)
{
if (luminosityPercent >= 80)
{
turnRed();
screensToClose = 3;
}
else if (luminosityPercent >= 50)
{
turnYellow();
screensToClose = 2;
}
else
{
turnGreen();
screensToClose = 1;
}
moveScreens(screensToClose);
Serial.print("LDR %: ");
Serial.println(luminosityPercent);
previousLuminosityPercent = luminosityPercent;
}
}
void rgb(bool r, bool g, bool b)
{
digitalWrite(RED_PIN, r);
digitalWrite(GREEN_PIN, g);
digitalWrite(BLUE_PIN, b);
}
void turnRed()
{
rgb(1, 0, 0);
}
void turnYellow()
{
rgb(1, 1, 0);
}
void turnGreen()
{
rgb(0, 1, 0);
}
void openScreen(Screen screen)
{
screen.write(OPEN_ANGLE);
}
void closeScreen(Screen screen)
{
screen.write(CLOSE_ANGLE);
}
int getLuminosityPercent()
{
int ldrValue = analogRead(LDR_PIN);
return map(ldrValue, MIN_LDR_VALUE, MAX_LDR_VALUE, 100, 0);
}
int moveScreens(int quantityOfScreensToClose)
{
quantityOfScreensToClose--;
for (int i=0; i<3; i++)
{
if (i <= quantityOfScreensToClose)
closeScreen(screens[i]);
else
openScreen(screens[i]);
}
}