我试图同时运行两个" Blink" -esque功能。
我在其他地方找到了一些代码,可以让我这样做并修改它!大。
然而,我要做的是按照惯例每隔1000毫秒打开和关闭一个LED,但另一个LED以奇数模式闪烁,例如ON为3000ms,OFF为100ms,ON为100ms,OFF为200ms然后循环回来。
为了实现这一点,我尝试在我找到的代码中添加一个随机函数,但我不喜欢它的外观。它看起来像一个闪烁的LED干扰或其他东西,如无线电发射器或其他什么。我试图复制一个旧的闪烁灯泡,这意味着它总是必须打开的时间长于它关闭的时间。基本上它需要为ON / HIGH以便更长时间"一段时间然后被几次短暂的ON和OFF闪烁中断
所以我正在寻找帮助,帮助我如何在更具体的一系列闪烁中协调第二个LED的开启和关闭。
这是我目前使用的代码:
/* Blink Multiple LEDs without Delay
*
* Turns on and off several light emitting diode(LED) connected to a digital
* pin, without using the delay() function. This means that other code
* can run at the same time without being interrupted by the LED code.
*/
int led1 = 13; // LED connected to digital pin 13
int led2 = 12;
int value1 = LOW; // previous value of the LED
int value2 = HIGH; // previous value of the LED
long time1 = millis();
long time2 = millis();
long interval1 = 1000; // interval at which to blink (milliseconds)
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(0));
pinMode(led1, OUTPUT); // sets the digital pin as output
pinMode(led2, OUTPUT);
}
void loop()
{
unsigned long m = millis();
if (m - time1 > interval1){
time1 = m;
if (value1 == LOW)
value1 = HIGH;
else
value1 = LOW;
digitalWrite(led1, value1);
}
long interval2 = random(100,1500);
if (m - time2 > interval2){
time2 = m;
if (value2 == LOW)
value2 = HIGH;
else
value2 = LOW;
digitalWrite(led2, value2);
}
Serial.println(interval2);
}
答案 0 :(得分:0)
尝试这样的事情:
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(0));
pinMode(led1, OUTPUT); // sets the digital pin as output
pinMode(led2, OUTPUT);
}
long interval2 = random(100,1500);
void loop()
{
unsigned long m = millis();
if (m - time1 > interval1){
time1 = m;
if (value1 == LOW)
value1 = HIGH;
else
value1 = LOW;
digitalWrite(led1, value1);
}
if (m - time2 > interval2){
time2 = m;
if (value2 == LOW) {
value2 = HIGH;
interval2 = random(100, 1500);
} else {
value2 = LOW;
interval2 = random(100, 200);
}
digitalWrite(led2, value2);
}
答案 1 :(得分:0)
这总是需要不到一秒的时间才能运行,这样您就可以回到主循环并确保不会错过另一个LED的1秒开/关:
void flicker(){
boolean state = false;
int r = random(20, 175);
for(int i = 0; i < 5; i++){
digitalWrite(led2, state);
state = !state;
delay(r);
r = random(20, 175);
}
digitalWrite(led2, HIGH);
}
顺便说一下。我正在替换这个切换代码:
if (value2 == LOW)
value2 = HIGH;
else
value2 = LOW;
digitalWrite(led2, value2);
用这个:
state = !state;
digitalWrite(led2, state);
现在,随机调用flicker()
;也许每15-45秒或任何你觉得合适/现实的东西。