2

I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?

int blue_led=10;

void setup() {  
  pinMode(blue_led,OUTPUT);
}

void loop() {

  int voltage=0;

  for(int i=0;i<=255;i+1){

    analogWrite(blue_led,voltage);
    voltage=voltage+1;
    delay(8);
  }
   int volts=255;

   for(int i=0;i<=255;i+1){

    analogWrite(blue_led,volts);
    volts=volts-1;
    delay(8);
   }


}
2

your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)

  • i could be used instead of voltage and volts, couldn't it? I mean, is max voltage 255? – brasofilo May 31 at 1:09
  • Sure, 'i' could be used, because 255 is indeed the maximum allowed value for the PWM pins. But again, the 'i' in the OP's code will never go past '0', until the for() loop is fixed. Here's a handy article about it... allaboutcircuits.com/projects/using-the-arduinos-analog-io – Randy May 31 at 1:14
  • 1
    Ah i understand. I just made the changes and it works perfectly! Thanks so much! – ThisUsernameHasBeenTaken May 31 at 1:37
  • Thanks for the explanation, Randy. @ThisUsernameHasBeenTaken, if the answer solved your problem you can mark it as accepted (see help center) – brasofilo May 31 at 3:26
  • Just done :) Thanks – ThisUsernameHasBeenTaken May 31 at 12:39

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.