1

Guys please help me out in verifying my program for my project -- led fading effect using a push button.

My project is simple, I want to start the LED fading effect (i.e., glowing and dimming one after another) at one click on the push button that is pushing and then leaving the push button and on my another click I want the effect to get off.

The main problem is coming in the programming part and rest all the circuit and components are fine.

THIS IS MY SKETCH :-

int ledpin = 9;
int buttonpin = 8;
boolean buttonpressed = false;   // to check whether the button was pressed //
int brightness = 0;
int fadeamount = 5;

void setup ()
{ 
pinMode (ledpin, OUTPUT);
pinMode (buttonpin,INPUT);
digitalWrite (ledpin,LOW);
}

void loop ()
{      
if ( digitalRead (buttonpin) == HIGH)
 { 
  buttonpressed = true;
 }

 else {
     if ( buttonpressed = true && digitalRead(ledpin) == LOW)
       {
           brightness = brightness + fadeamount;
           if ( brightness == 0 || brightness == 255)
            { 
             fadeamount = -fadeamount;}
             analogWrite(ledpin, brightness);
             delay (30);
             buttonpressed = false;
        }
      if (buttonpressed == true && analogRead(ledpin) == brightness)
        {
          digitalWrite(ledpin,LOW); 
          buttonpressed = false;
        }
   }
 }

THIS IS THE CIRCUIT DIAGRAM

9
  • 1
    Where's the resistor on your LED? – Majenko Mar 22 '16 at 16:43
  • 1
    digitalWrite (buttonstate,HIGH); - What is that supposed to achieve?! – Majenko Mar 22 '16 at 16:44
  • 1
    int fadeamount = 51; - That's a huge amount to fade by... – Majenko Mar 22 '16 at 16:45
  • bro brightness doesn't matter i can change it any time to 5 or something low.......and about digitalWrite (buttonstate,HIGH); i used it to let the button state as high even after i leave the pushbutton so that the LED doesn't get off !! – MrDeepThought Mar 22 '16 at 16:52
  • i used it to let the button state as high even after i leave the pushbutton so that the LED doesn't get off !! well it doesn't. I don't know how you thought that might work. You're actually writing HIGH to either pin 0 or pin 1. – Majenko Mar 22 '16 at 16:53
2

I changed things a bit and got a solution

int led = 3;
int buttonpin = 8;
boolean waspressed = false;

int inertia = 10;

void setup (){ 
  pinMode(buttonpin,INPUT);
  pinMode(led,OUTPUT);
  analogWrite(led,0);
}

void loop(){
  if(digitalRead(buttonpin) == HIGH){
    waspressed = true;
  }else{
     if (waspressed == true){
       fadeLed(digitalRead(led), inertia);
       waspressed = false;
     }
  }
}

void fadeLed(boolean input, int inertia){
  for(int state=0;state<256;state++){
    if (input==LOW){
      analogWrite(led, state);
    }else{
      analogWrite(led, 255-state);
    }
    delay(inertia);
  }
}

I created a function called fadeLed that receives two arguments: The actual state of the led and the delay - in miliseconds - that is going to determine how long the fading is going to last.

You can see that the rest of the code is pretty much the one you got in the other question you asked. This is because we already got a good code to control the behavior of the button, so its a good practice to keep it and just change what you want to be changed: to fade instead of blink. So we just change a single line and create a function to be called by that line. Functions are a good way to keep a clean code and are a good programming practice. They make the code easy to read and maintain.

The function fadeLed() uses PWM to fade the led. In Arduino Uno, PWM is available in digital pins 3, 5, 6, 9, 10, and 11. This may change according to the model you are using. It's very important to understand PWM so you can know why analogWrite() is used in a digital pin.

If you check the documentation of analogWrite(), you are going to see that for most of the Arduino boards the default resolution is 8 bits, i.e, 0 to 255. To use all this 256 values to fade the led, a for loop is used. If you are not used to for loops, I strongly recommend you to read the documentation.

The for loop is programed to go through 256 iterations - the variable state going from 0 to 255. At each iteration, the value of state is incremented by 1. When state gets to be equal to 256, the loop ends itself. Every iteration verifies the value of input, which is just the state of the led when the button was released. This value is passed to the function only when the button is released, but the function uses it internally at every iteration. If input is LOW, it means that the led was off, so analogWrite(led, state); uses the value of state - increasing at every iteration - to fade the led, turning it on. If input is HIGH, it means that the led was on, so analogWrite(led, 255-state); will fade the led turning it off. In this case, 255-state is just a way to set a range starting at 255 and ending at 0 while using a range that we already have - state - that starts at 0 and ends at 255.

The last line is just to set how long the fade action is going to last. To be more specific, delay(inertia) determine how long each iteration is going to last. So, when you set inertia to 10, will you see that fading will take 10(miliseconds)*255(iterations) + execution times =~ 2,6 seconds. I chose this name when I was coding and I'm not sure now if it was the better one. Maybe something like duration will have a more clear meaning. If you want to set the duration of the fade on your code - instead of the duration of each iteration - you can to something like

int fadeDuration = 3000; //duration of fade in ms

...


void fadeLed(boolean input, int inertia){
  for(int state=0;state<256;state++){
    if (input==LOW){
      analogWrite(led, state);
    }else{
      analogWrite(led, 255-state);
    }
    // delay in every iteration to achieve 3 seconds in total.
    delay(fadeDuration/256); //=(total fading duration)/(number of iterations)
  }
}

Hope this is clear. Don't forget to check the links I placed, they are all VERY important.

2
  • Can you explain me the use of inertia ? Also how are you using the fadeLed fuction ? – MrDeepThought Apr 19 '17 at 17:57
  • 1
    I tried to describe what I did. Check out – rvbarreto Apr 19 '17 at 21:54
3

The 1k (pulldown-)resistor must be placed at the other side of the button (the pin8 side, not the 5v side).

The led needs a resistor, to limit the current.

There is no need for the buttonstate variable, as you can just check the brightness to see if the PWM value must be changed.

int ledpin = 9;
int pushbutton = 8;

int brightness = 0;
int fadeamount = 1;

void setup ()
{ 
  pinMode (ledpin,OUTPUT);
  pinMode (pushbutton,INPUT);
}

void loop ()
{ 
  if( digitalRead(pushbutton)==HIGH && brightness<255 )
  {
    // fade in led 
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton)==LOW && brightness>0 )
  {
    // fade out led
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin,brightness);
    delay (1);
  }

}
1
  • but this program will only work when i will push or leave the push button not like i wanted............i wanted the fading effect to continuously work even after leaving the push button. it should be like on first click(pressing and leaving) the fading effect should start and on another click the LED turns off again if i click the push button the fading effect should start and on my another click the LED turns off. – MrDeepThought Mar 27 '16 at 10:38
2

try this, its simple and easy to understand,

int ledPin = 9;
int btnPin = 8;
int brightness = 0;
int btnState = LOW;
bool trigger = LOW;
void setup ()
{
  pinMode (ledPin, OUTPUT);
  pinMode (btnPin, INPUT);
}

void loop ()
{
  if ( digitalRead(btnState) && !btnState)
  {
    if (trigger)
    {
      for (int i = 0; i < 256; i++)
      {
        analogWrite(ledPin, i);
        // wait for 30 milliseconds to see the dimming effect
        delay(30);
      }
    }
    else
    {
      for (int i = 255; i >= 0; i--)
      {
        analogWrite(ledPin, i);
        // wait for 30 milliseconds to see the dimming effect
        delay(30);
      }
    }
    trigger = !trigger;
  }
  btnState = digitalRead(btnState);
}
1
  • You might want to add some delay, or the fade is so fast you can see it. – Gerben Mar 22 '16 at 17:08
1

you should break down the code into two pieces, one to read the button and another to fade the led.

to fade an led, you just need to change its brightness and hold at that brightness for a short period of time. to drive the led at its brightness, use pwm.

that's all there is.

fancier ones will try to do a gamma correction but to just get started, the above is sufficient enough.

0

There are basically two parts to your program and it's best if you deal with them completely separately:

  1. Reading a push button to turn fading on or off
  2. Fading if fading is turned on

Start by making an LED fade all the time. The Fade example can help you with that.

Then as a separate sketch program the button to turn an LED on or off each time you press it.

Once you have those working change the LED in the second sketch to setting a flag, and make the code from the first sketch look at that flag.

6
  • actually i had tried to make this sketch after learning to fade an LED and toggling the the LED on and off using push button but something is still getting wrong. – MrDeepThought Mar 22 '16 at 16:59
  • Show us your LED toggling code. – Majenko Mar 22 '16 at 17:01
  • @Majenko Tehee, try not to use the word "fool". But you've put some quite some effort into the question/answer which somewhat justifies it. But keep in mind that the way StackExchange works, might not be as trivial to new or foreign users (again and again indeed). – Paul Mar 22 '16 at 17:13
  • @Paul I was doing my Mr T impression. I guess these kids these days wouldn't recognise him if he jumped up in front of them and punched them in the face... – Majenko Mar 22 '16 at 17:14
  • @Majenko, Ahaha, I was already thinking something, but such things can be hard to spot (depending on your frame of reference). In Germany, Mr. T wouldn't talk English (they've got those annoying voice-over things on TV) ;D and some Arduino Engineers might indeed not know him, yet. Fact of the day: "A snickers commercial (featuring Mr. T) was once banned from TV youtube.com/watch?v=Ona7QYULRVE" – Paul Mar 22 '16 at 17:22

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.