我想在Arduino程序中运行循环三次以使led闪烁3次。如何运行循环3次并退出loop.how以在循环中使用return语句?一旦领先,持续1秒然后下车。
int LedPin = 13;
int Loops = 1;
void setup() {
pinMode(LedPin, OUTPUT);
}
void loop() {
digitalWrite(13, LOW);
Loops = Loops + 1;
if ( Loops < 3 )
{
digitalWrite(13, HIGH);
delay(2000);
}
else {
digitalWrite(13, LOW);
exit(0);
}
}
答案 0 :(得分:0)
arduino循环永远循环。
https://www.arduino.cc/en/Reference/Loop
如果你想停止运行那个循环,你可以将arduino置于睡眠模式:
http://playground.arduino.cc/Learning/ArduinoSleepCode
我还建议您彻底了解流量控制的工作原理(以及可能的状态机)。请参阅第5章。控制结构:
答案 1 :(得分:0)
如果我们&#34;展开&#34; loop
函数,我们得到:
// Loops is 1 on the first call.
digitalWrite(13, LOW);
Loops = Loops + 1;
// Loops is now 2
if (Loops < 3)
{
// So, we enter here...
digitalWrite(13, HIGH);
delay(2000);
}
else
{
// but not here
digitalWrite(13, LOW);
exit(0);
}
// Next call:
// Turn off the light.
digitalWrite(13, LOW);
Loops = Loops + 1;
// Loops is now 3
if (Loops < 3)
{
// So we don't enter here
digitalWrite(13, HIGH);
delay(2000);
}
else
{
// but we enter here
digitalWrite(13, LOW);
// Which exits
exit(0);
}
所以你打开LED一次,然后将其关闭然后退出 如果您调整循环计数器,您将关闭LED,然后立即再次打开它,这样看起来会更长时间。
您可能希望在每个循环上执行完整的开/关循环 - 如下所示:
int LedPin = 13;
int Loops = 0;
void setup() {
pinMode(LedPin, OUTPUT);
digitalWrite(LedPin, LOW);
}
void loop() {
Loops = Loops + 1;
if (Loops <= 3)
{
digitalWrite(LedPin, HIGH);
delay(2000);
digitalWrite(LedPin, LOW);
delay(2000);
}
else
{
exit(0);
}
}
答案 2 :(得分:0)
void setup() {
// initialize digital pin 13 as an output.
for (int i=0; i < 4 ; i++)
{
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
}
// the loop function runs over and over again forever
void loop() {
}
答案 3 :(得分:-1)
int LedPin = 13;
void setup() {
pinMode(LedPin, OUTPUT);
function() ; //call this function whatever you want
}
void function()
{
digitalWrite(LedPin, HIGH);
delay(1000) //add the desired delay
digitalWrite(LedPin, LOW);
delay(1000) //add the desired delay
digitalWrite(LedPin, HIGH);
delay(1000) //add the desired delay
digitalWrite(LedPin, LOW);
delay(1000) //add the desired delay
digitalWrite(LedPin, HIGH);
delay(1000) //add the desired delay
digitalWrite(LedPin, LOW);
delay(1000) //add the desired delay
}