【问题标题】:Arduino RGB LED random PWM LevelArduino RGB LED 随机 PWM 电平
【发布时间】:2017-02-22 07:29:57
【问题描述】:

我正在尝试创建一个程序,该程序将从给定的阵列中随机选择 RGB LED 的 PWM 值。它适用于第一种颜色,蓝色。然后我嵌套了第二种颜色,绿色,我从显示中释放了蓝色,只显示了绿色。

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

}

【问题讨论】:

  • 正确格式化您的代码将对每个人(包括您自己)都有很大帮助。
  • 为什么greenVariable = random(0,255),你只有9个亮度值。此外,您的循环是无限的,没有退出条件。
  • 我也看不到 PWM 这里可能是 analogWrite 函数的用途,但没有上下文我们不知道它的作用。操作数是什么?您的 LED 是如何连接到 MCU 的?你买的是哪个MCU?你用的是什么 PWM(软件、定时器/计数器、PWMA 模块)? Arduino 不是魔术词,它只是一个框架,所以你看不到/不明白你在做什么......这段代码放在哪里/调用(主线程,ISR,......)?
  • 迈克尔,你的权利来自以前的编码,应该已经改变了。

标签: c++ arduino embedded rgb led


【解决方案1】:

你有两个问题:

首先,您将绿色的“for 循环”连接到(!)蓝色的 for 循环中。基于循环无限运行的事实,您只循环通过第二个 for 循环。

第二个问题(也许不是问题,但是您看不到 Blue 的原因)是您将 blueVariable 初始化为 0。 如果您第一次运行,则将值 0 写入 PWM 引脚。之后您更改变量,但不要写入 PWM 引脚,因为您会陷入“无限绿色循环”。

顺便说一句,就像 Michael 在 cmets 中所说的那样,您应该将数组中的 255 更改为 8,并且您应该将数组中的最后一个值 (256) 更改为 255,因为 8 位 PWM 表示 0-255 的 256 个值。

例子:

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

【讨论】:

  • 谢谢 H. Puc。一些错误是由于从增加和减少的双向更改代码(因此是 for 循环),我应该从头开始每次尝试而不是修改现有代码。阅读您的编辑并应用它们后,我知道我的错误在哪里。事实上,我能够正确地将我的 RGB 的红色部分添加到正确的工作顺序中。
猜你喜欢
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多