需要帮助 - 如何在if语句中退出for循环?

时间:2016-02-13 00:47:43

标签: arduino

我试图在if语句中运行for循环,但它不断重复。当我按下引脚2上的一个按钮时,我基本上希望引脚4闪烁6次。当z在for循环中变成6时,if语句使z重置为0并且for循环重新开始。因此,引脚4上的LED持续闪烁。任何人都可以帮助它只闪烁6次?这是代码:

int switchState = 0;

void setup() 
{
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(2, INPUT);

}

void loop() 
{
  switchState = digitalRead(2);
  if (switchState == LOW)
  {
    digitalWrite(5, LOW);
    digitalWrite(4, LOW);
  }
  else
  {
    digitalWrite(5, HIGH);
    for (int z=0; z<6; z++)
    {
      digitalWrite(4, HIGH);
      delay(100);
      digitalWrite(4, LOW);
      delay(100);
    }
  }

}

1 个答案:

答案 0 :(得分:3)

试试这个:

void setup() 
{
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(2, INPUT);
}

void loop() 
{

  //Deactivate all leds
  digitalWrite(5, LOW);
  digitalWrite(4, LOW);

  if (digitalRead(2) == HIGH) { //If the button is pressed... 
    digitalWrite(5, HIGH);

    //blink
    for (int z=0; z<6; z++)
    {
       digitalWrite(4, HIGH);
       delay(100);
       digitalWrite(4, LOW);
       delay(100);
    }

    while (digitalRead(2) == HIGH) { // Wait until release the button
       delay(10); 
    }

  }

}