I hope the LED can fade out a period of time. Also, I hope I can switch off the LED immediately when it is fading, but I only can fade out.
const int buttonPin = 2;
const int ledPin = 9;
const int fadingDelay = 20000;
int buttonState = 0;
boolean fadingState = false;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check whether the button was pressed
if (buttonState == HIGH) {
buttonState = LOW;
// check the current LED status (on/off)
if (fadingState == false) {
// turn on the LED
for (int i = 255; i >= 0; i -= 5) {
if (buttonState == HIGH && fadingState == true) {
analogWrite(ledPin, 0); //immediately off
i=-1;
}
analogWrite(ledPin, i);
delay(fadingDelay);
}
fadingState = false; // save the current LED state (on/off)
}
}
}