Search code examples
loopsarduinofadeled

Could there be a way to escape this loop?(problem with fade and leds)


int led1 = 3;
int led2 = 5;
int led3 = 6;
int led4 = 9;
int m = 1;
int brightness = 10;
int fadeAmount = 5;
int led;
int one = 1;

void setup()
{
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
}

void loop()
{
  if (m == 4 or m == 1) {
    one = -one;
  }
  if (intensite <= 5){
      m = m + one;
    }
  if (m == 1) {
    led = led1;
  }
  if (m == 2) {
    led = led2;
  }
  if (m == 3) {
    led = led3;
  }
  if (m == 4) {
    led = led4;
  }
  

    brightness = brightness + fadeAmount;

   if (brightness <= 5 or brightness >= 255) {
     fadeAmount = -fadeAmount;
   }
   analogWrite(led,brightness);
   delay(10);
}

When I run this part of the code, it just gets stuck in a infinite loop at the top led and it does not go back down the way it should which I fail to see. It would be of great help if one could help me understand my mistake. The aim is to make a code that lights leds from right to left (led1 to led4) then left to right (led4 to led1), not simply turning them on but fading them.


Solution

  • I tried my best to stay as close to your code as possible. So your code didn't work because it don't make much sense. Why would you make this one variable? It just complicated all the things. Just put a boolean which indicates whether you are going left or not and change it based on the current value of m. Here is how:

    int led1 = 3;
    int led2 = 5;
    int led3 = 6;
    int led4 = 9;
    int m = 1;
    int brightness = 10;
    int fadeAmount = 5;
    int led;
    bool goingLeft;
    
    void setup()
    {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
    }
    
    void loop()
    {
      if (m == 1) { // If we are on the right side we set goingLeft to true
        goingLeft = true;
      }else if(m == 4){ // If we are on the left side we set goingLeft to false
        goingLeft = false;
      }
      if (brightness <= 5 && goingLeft){ // if we are moving left then we increment the m variable
          m++;
      }else if(brightness <= 5){ // if we are moving right we decrement it
        m--;
      }
      if (m == 1) {
        led = led1;
      }
      if (m == 2) {
        led = led2;
      }
      if (m == 3) {
        led = led3;
      }
      if (m == 4) {
        led = led4;
      }
        brightness = brightness + fadeAmount;
    
       if (brightness <= 5 or brightness >= 255) {
         fadeAmount = -fadeAmount;
       }
       analogWrite(led,brightness);
       delay(10);
    }
    

    If I were you I would do this in a completly diffrent way by using for loops but as I said earlier I tried to stay as close to your code as I could.

    Also I saw that you used or in your code. Don't do it!!! In C languages the or operator is || not or