const int doorPin = 4;        // Door sensor input pin
const int buttonPin = 2;      // Button input pin (connected to ground when pressed)
const int ledPin = 3;         // LED output pin
int doorState = LOW;          // Current state of the door sensor
int lastDoorState = LOW;      // Previous state of the door sensor
int buttonState = HIGH;       // Current state of the button
int lastButtonState = HIGH;   // Previous state of the button
unsigned long lastDebounceTime = 0;  // Time when button state last changed
unsigned long debounceDelay = 50;    // Delay to avoid button bouncing
int fadeValue = 0;            // PWM value for LED brightness

void setup() {
  pinMode(doorPin, INPUT);
    pinMode(buttonPin, INPUT_PULLUP);  // Use internal pull-up resistor for button
      pinMode(ledPin, OUTPUT);
      }

      void loop() {
        doorState = digitalRead(doorPin);
          buttonState = digitalRead(buttonPin);

            if (doorState != lastDoorState) {
                if (doorState == HIGH) {
                      fadeValue = 0;  // Start fading LED from off
                          } else {
                                fadeValue = 255;  // Set fade value to max for gradual off
                                    }
                                        lastDoorState = doorState;
                                          }

                                            if (buttonState != lastButtonState) {
                                                lastDebounceTime = millis();
                                                  }

                                                    if ((millis() - lastDebounceTime) > debounceDelay) {
                                                        if (buttonState == LOW) {
                                                              fadeValue = 255 - fadeValue;
                                                                  }
                                                                      lastButtonState = buttonState;
                                                                        }

                                                                          analogWrite(ledPin, fadeValue);

                                                                            delay(50);  // Delay for smooth fading effect
                                                                            }