Arduino RGB LED随机PWM级别

Arduino RGB LED random PWM Level

本文关键字:PWM 级别 随机 LED RGB Arduino      更新时间:2023-10-16

我正在尝试创建一个程序,该程序将随机选择从给定数组LED的RGB值。它与第一种颜色蓝色一起工作正常。然后,我以第二种颜色筑巢,绿色,我从显示中放开蓝色,只有绿色显示。

void loop() {
  // put your main code here, to run repeatedly:
  int x[9] = {0, 32, 64, 96, 128, 160, 192, 224, 256};  //setup Array X for brightness options
  int blueVariable = 0;                                 //Blue LED
  int greenVariable = 0;                                //Green LED
  for (int blueLed = 0; blueLed > -1; ) {               //for loop to choose PWM option
    analogWrite(11, x[blueVariable]);                   //Initilize the PWM function on pin 11 to brightness of blueVariable
  //  if (blueLed == 255) blueLed = 0;                    //
    blueVariable = random(0,8);                         //Random function to decide on blueVariable value
  delay(500);

     for (int greenLed = 0; greenLed > -1; ) {
       analogWrite(10, x[greenVariable]);
      //  if (g == 255) g = 0;             // switch direction at peak
        greenVariable = random(0,255);
     delay(500);
     }
  }
}

您有两个问题:

首先,您将" for Loop"挂在(!)中的绿色中,用于蓝色。基于以下事实:循环运行无限,您只需循环循环以进行循环。

第二个问题(也许不是问题,但是您看不到蓝色的原因)是您对bluevariable的初始化为0。如果第一次运行,则将值0写入PWM PIN。之后,您更改了变量,但请勿写入PWM PIN,因为您陷入了"无限的绿色环"。

btw,就像迈克尔(Michael)的评论中所说的那样,您应该将255更改为8,并且在您的数组中您应该将最后一个值(256)更改为255>

示例:

int x[9] = {0, 32, 64, 96, 128, 160, 192, 224, 255};    // Changed Value
void loop() {
  int blueVariable = 0;                                 //Blue LED
  int greenVariable = 0;                                //Green LED
  while(1) {                                            // Because it was infinite already i changed it to while(1)
    blueVariable = random(0,8);                         //Put in front of analogWrite()
    analogWrite(11, x[blueVariable]);                   
    delay(500);
    // Deleted the scond loop
    greenVariable = random(0,8);                        // Value changed from 255 to 8; Also put in front of analogWrite
    analogWrite(10, x[greenVariable]);
    delay(500);
  }        
}