// Include required libraries
#include <Arduino.h>
// Pin Definitions
const int LIGHT_SENSOR_PIN = 2; // Replace with your light sensor pin
const int LED_PIN = 4; // Replace with your LED pin
const int BUTTON_PIN = 23;
// Parameters
const int PWM_FREQUENCY = 1000; // PWM frequency
const int PWM_RESOLUTION = 8; // PWM resolution (8 bits)
int callibration = 0;
int MinAmbient = 0;
int MaxAmbient = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Initialize Light Sensor
pinMode(LIGHT_SENSOR_PIN, INPUT);
// Initialize LED
ledcSetup(0, PWM_FREQUENCY, PWM_RESOLUTION);
ledcAttachPin(LED_PIN, 0);
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
// Read light sensor value
int lightValue = analogRead(LIGHT_SENSOR_PIN);
int Push_button_state = digitalRead(BUTTON_PIN);
// Calibration
while(callibration == 0){
Serial.println("Turn off all your lights and push the button.");
while(Push_button_state == 0){
Push_button_state = digitalRead(BUTTON_PIN);
delay(100);
lightValue = analogRead(LIGHT_SENSOR_PIN);
MinAmbient = lightValue;
}
Push_button_state = 0;
delay(1000);
Serial.println("Turn on all your lights and push the button.");
while(Push_button_state == 0){
Push_button_state = digitalRead(BUTTON_PIN);
delay(100);
lightValue = analogRead(LIGHT_SENSOR_PIN);
MaxAmbient = lightValue;
}
callibration = 1;
}
// Update LED brightness using PWM
int ledBrightness = map(lightValue, MaxAmbient, MinAmbient, 0, 255);
if(ledBrightness < 0){
ledcWrite(0, 0);
}
else{
ledcWrite(0, ledBrightness);
}
// Print the sensor and LED brightness values
Serial.print("MinAmbient: ");
Serial.println(MinAmbient);
Serial.print("MaxAmbient: ");
Serial.println(MaxAmbient);
Serial.print("Sensor Reading: ");
Serial.println(lightValue);
Serial.print("LED Brightness: ");
Serial.println(ledBrightness);
delay(1000); // Adjust the delay as needed for your application
}