有没有办法摆脱这个循环?(淡入淡出和 LED 的问题)

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

当我 运行 这部分代码时,它只是卡在顶部 led 的无限循环中,并且不会按我看不到的方式返回。如果有人能帮助我理解我的错误,那将有很大帮助。目的是制作一个代码,从右到左(led1 到 led4)然后从左到右(led4 到 led1)点亮 LED,而不是简单地打开它们,而是使它们褪色。

我尽最大努力尽可能接近您的代码。所以你的代码没有用,因为它没有多大意义。你为什么要创建这个 one 变量?这只会让所有事情变得复杂。只要放一个boolean表示你是否向左走,然后根据m的当前值改变它。方法如下:

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

如果我是你,我会使用 for 循环以一种完全不同的方式来做到这一点,但正如我之前所说,我尽可能地接近你的代码。

另外 我看到您在代码中使用了 or。不要这样做!在 C 语言中,or 运算符是 || 而不是 or