我如何随机选择Arduino引脚输出



我有一系列八个led,我试图随机淡出,从ON开始。这是我到目前为止的进展

#define LED1 2
#define LED2 3
#define LED3 4
#define LED4 5
#define LED5 6
#define LED6 7
#define LED7 8
#define LED8 9
void setup() {
pinMode(LED1,output);
pinMode(LED2,output);
pinMode(LED3,output);
pinMode(LED4,output);
pinMode(LED5,output);
pinMode(LED6,output);
pinMode(LED7,output);
pinMode(LED8,output);
}
    void cycleLED() {
        timeOn = random(600,1800);
        timeOff = random(600,1800);
        for (fadeOut = 255; fadeOut > 0; fadeOut--) { 
            analogWrite(LED, fadeout);
            delay(timeOff); 
        }
        for (fadeIn = 0;fadeIn < 255; fadeIn++) { 
            analogWrite(LED,fadeIn);      
            delay(timeOn); 
        }
    }

这就是我被卡住的地方。我想做一些类似于下面伪代码的事情。

activeLED = random(2,10);             // choose a random LED pin
LEDtoCycle = pinNumber-activeLED;     // set the active LED to the random LED pin 
cycleLED(pinNumber-activeLED);        // run cycleLED on the active LED

我的意图是随机选择一个LED,然后在该LED上运行cycleLED,无限重复。然而,我很难想出一个好的方法来做到这一点。我如何将pin变量传递给cycleLED()?或者我应该重复#define一个单一的,随机的LED?或者我应该硬编码八个单独的cycleLED1(), cycleLED2(), cycleLED3()实例,等等。

提示或建议?

可以让cycleLED函数接受如下参数:

void cycleLED(int led)

然后在你的analogWrite调用中使用led变量来代替你目前拥有的神秘的led东西。

最新更新