Arduino RGB LED随机PWM电平

问题描述:

我正在尝试创建一个程序,它将随机选择给定阵列中的RGB LED的PWM值。它适用于第一种颜色蓝色。然后我以第二种颜色嵌套,绿色,我从显示中松开蓝色,只有绿色显示。Arduino 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); 
    } 
    } 

} 
+1

正确格式化你的代码是给大家一个巨大的帮助(包括你自己)。 –

+4

为什么'greenVariable = random(0,255)',你只有9个亮度值。此外,你的循环是无止境的,没有退出条件。 – Michael

+0

另外,我看到没有** PWM **这里可能是'analogWrite'函数的用途,但没有上下文我们不知道它的功能。什么是操作数?你的LED如何连接到MCU?你有哪个MCU?你用什么PWM(SW,T/C,PWMA模块)? Arduino不是魔术词,它只是一个框架,所以你看不到/明白你在做什么......这个代码放置/调用的位置(主线程,ISR,...)? – Spektre

就有两个问题:

首先你迷上你的 “for循环” 在绿色的for循环蓝色(!)。基于循环运行无限的事实,你只能循环第二个for循环。

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

顺便说一句,就像在Michael的评论中说的那样,你应该把255改成8 AND,你应该把最后一个值(256)改成255,因为8bit 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); 
    }   
} 
+0

谢谢H. Puc。其中一些错误是通过改变代码来增加和减少bi的正确性(因此是for循环),我应该从头开始每一次尝试,而不是修改现有的代码。阅读您的编辑并应用它们后,我会看到我的错误在哪里。事实上,我能够正确地将我的RGB的红色部分添加到正确的工作顺序。 –