PWM Challenge

This question is from Jim Therrien, and comes from this lesson:

The Question:

So I was doing the challenge for fading LEDS using PWM and I found that my code wasn’t working.

The LEDS were not coming on. I did manage to get them to fade but only if the brightness variable was GLOBAL.

I don’t understand the reason for this. Can you explain?

//This sketch demonstrates the analogWrite function to utilize Pulse Width Modulation

// Declare and initialize the brightness variable

byte brightness = 0;

void setup() {
  /* Because we are using the analogWrite function
    we do not need any setup as it is the only function
    being called and with this function we do not need to set the pin as an OUTPUT */


}

void loop() {
  // Declare and initialize variable for the LEDs, delay and the amount to fade by
  byte LED_1 = 6;
  byte LED_2 = 5;
  byte Pause = 30;
  byte fadeIncrement = 1;

  // Set up PWM.
  analogWrite(LED_1, brightness);
  analogWrite(LED_2, brightness);
  delay(Pause);
  // increment the brightness variable.
  brightness = brightness + fadeIncrement;
  /* to start brightness is declared as 0.
    Then brightness is incremented by 1 and now
    brightness is equal to 1. As the loop runs each time brightness is
    incremented and stores as the new value for
    brightness*/
  delay(Pause);
}

You Challenge:

In the sketch, why does the brightness variable need to be global in order for the program to operate as expected?

Hints:

Put the line of code byte brightness = 0;  in the loop, why doesn’t the LED fade in and out?

My Thoughts:

This is what I came up with…
[fvplayer src=”https://vimeo.com/334002897″ transcript=”auto” splash=”https://i.vimeocdn.com/video/780160467_1280x720.jpg?r=pad” caption=”Jim Therrien – PWM”]

You Thoughts:

Any thoughts on this?  Trying to figure out where to declare your variables can be tough to figure out sometimes.

Leave a Comment