0

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)
  }
}
}
  • 1
    see the BlinkWithouDelay example. now your sketch stops for 20 seconds. – Juraj Apr 20 at 5:32
  • Your code is a mess, and won't work properly. You need to clearly define what you want to do before we can help you. – Duncan C Apr 20 at 23:47
0

I can't see anywhere where you are assigning fadingState as true.I can't understand this part

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);   
    }

If you are entering in a if condition with statement fadingState as false. Then in for loop you are having a if condition in which statement is fadingState == true.If you are entering in as a False then why are you looking for True Condition.

Then if you manage to sort that add break; in that if condition so that when LED turns OFF you will exit that for Loop.

And Here you are setting the button state as low buttonState = LOW if first If condition, then in that nested if without reading the buttonState you still looking for it as HIGH.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.