我正在尝试创建一个程序,该程序将从给定数组中随机选择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);
}
}
}
答案 0 :(得分:1)
你有两个问题:
首先,你勾勒出你的" for循环"对于(!)中的绿色,蓝色的for循环。基于循环运行无限的事实,你只能循环遍历第二个for循环。
第二个问题(也许不是问题,但是你没有看到蓝色的原因)是你将blueVariable初始化为0。 如果是第一次运行,则将值0写入PWM引脚。之后你改变了变量,但是没有写入PWM引脚,因为你陷入了无限的绿色循环"。
顺便说一句,就像迈克尔的评论中所说,你应该将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);
}
}