void setup() {
for (int i = 0; i < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
digitalWrite(1,HIGH);
digitalWrite(7,HIGH);
digitalWrite(11,HIGH);
delay(10000);
digitalWrite(1, LOW);
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
delay(2500);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(7,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
delay(5000);
digitalWrite(4,LOW);
digitalWrite(9,HIGH);
digitalWrite(11,LOW);
delay(10000);
digitalWrite(5, LOW);
digitalWrite(6, HIGH);
delay(2500);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
delay(5000);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
delay(2500);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
digitalWrite(3, LOW);
}
我们正在制作一个&#34;高级停车灯&#34;,所以 在代码中我需要添加它,以便在任何时候按下按钮,在循环结束时它将运行代码,我将如何做?
我尝试了几件事,但每次都无法解决问题,对此有什么简单的解决方案?
答案 0 :(得分:0)
按下按钮时是否尝试设置标记,然后在循环结束时检查是否已设置标记。
设置标志后,您知道该按钮已被按下,因此您可以执行该代码。这样的事情。
boolean buttonPressed = false;
void setup() {
for (int i = 0; i < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
digitalWrite(1,HIGH);
digitalWrite(7,HIGH);
digitalWrite(11,HIGH);
delay(10000);
digitalWrite(1, LOW);
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
delay(2500);
digitalWrite(1,LOW);
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(7,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
delay(5000);
digitalWrite(4,LOW);
digitalWrite(9,HIGH);
digitalWrite(11,LOW);
delay(10000);
digitalWrite(5, LOW);
digitalWrite(6, HIGH);
delay(2500);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
delay(5000);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
delay(2500);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
digitalWrite(3, LOW);
if(buttonPressed)
{
//code goes here
}
}
您需要添加以上内容的是按下按钮时设置buttonPressed = true
答案 1 :(得分:0)
如果我理解正确,无论是否按下按钮,您都希望整个循环运行,然后根据循环期间是否按下按钮来运行(或不运行)特殊代码。
如果是这样,你可以写一个函数my_delay(msec)并在循环内调用它而不是延迟。在my_delay中,如果按下按钮直到请求的时间已经过去,你将有一个循环重复测试:
static int lpressed = 0 ;
void my_repeat(int msec)
{
long start = millis() ;
for( ; millis()-start < msec; )
{
if (digitalRead(button_pin)==PRESSED)
lpressed = 1 ;
}
}
然后在循环结束时,您只需测试(并可能重置)变量lpressed并采取相应的行动:
void loop()
{
// your unconditional code goes here
if (lpressed)
{
lpressed = 0 ; // reset so we can check again in next cycle
// your conditional code goes here
}
}