#include <Arduino.h>
const int pirPin = 4; // PIR sensor pin
const int ledPin = 10; // LED pin
const int switchPin = 12; // External switch pin
int fadeUpSpeed = 25; // Adjust fade up speed
int fadeDownSpeed = 20; // Adjust fade down speed
int maxBrightness = 255; // Maximum brightness
unsigned long fadeDelay = 2000; // Delay before fading down (60 seconds)
unsigned long lastMotionTime = 0;
int currentBrightness = 0;
boolean lightOn = false;
boolean buttonPressed = false;
void setup() {
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
analogWrite(ledPin, 0);
}
void loop() {
boolean switchState = digitalRead(switchPin);
int motionValue = digitalRead(pirPin);
if (switchState == LOW && !buttonPressed) { // Button pressed
buttonPressed = true;
turnOnLED();
} else if (switchState == HIGH && buttonPressed) { // Button released
buttonPressed = false;
turnOffLED();
lastMotionTime = millis(); // Reset timer for PIR sensor
}
if (!buttonPressed) { // Control LED with PIR sensor when button is not pressed
if (motionValue == HIGH) {
if (!lightOn) {
fadeUp();
lightOn = true;
lastMotionTime = millis();
}
} else if (lightOn && millis() - lastMotionTime >= fadeDelay) {
fadeDown();
lightOn = false;
}
}
}
void turnOnLED() {
analogWrite(ledPin, maxBrightness);
currentBrightness = maxBrightness;
lightOn = true;
}
void turnOffLED() {
analogWrite(ledPin, 0);
currentBrightness = 0;
lightOn = false;
}
void fadeUp() {
for (int i = currentBrightness; i <= maxBrightness; i++) {
analogWrite(ledPin, i);
delay(fadeUpSpeed);
}
currentBrightness = maxBrightness;
}
void fadeDown() {
for (int i = currentBrightness; i >= 0; i--) {
analogWrite(ledPin, i);
delay(fadeDownSpeed);
}
currentBrightness = 0;
}