如何在Arduino中进行有限循环

时间:2016-02-18 22:59:26

标签: arduino arduino-uno

我是编码的初学者,尤其是Arduino。我一直在做很多项目,但我遇到了一个问题。我似乎无法弄清楚如何进行有限循环。我正在寻找类似于while循环的东西,它在四次后停止。这里是实施的地方,可以让您更好地了解我正在寻找的东西。

#include <Servo.h>

int thumbPin = 2;
int ndxPin = 3;
int midPin = 4;
int rngPin = 5;
int pnkyPin = 6;

Servo thumb;
Servo index;
Servo middle;
Servo ring;
Servo pinky;
void setup() {
  Serial.begin(9600);

  thumb.attach(thumbPin);
  index.attach(ndxPin);
  middle.attach(midPin);
  ring.attach(rngPin);
  pinky.attach(pnkyPin);
}
void loop() {
  /* I want this code in the comment to be ran four times, then continued on to the code after
  thumb.write(0);
  delay(20);
  thumb.write(0);
  index.write(0);
  middle.write(0);
  ring.write(0);
  pinky.write(0);

  thumb.write(150);
  index.write(150);
  middle.write(150);
  ring.write(150);
  pinky.write(150);
  */
  thumb.write(0);
  index.write(0);
  pinky.write(0);

  middle.write(0);
  thumb.write(150);
  pinky.write(150);
}

1 个答案:

答案 0 :(得分:7)

你想要一个for循环:https://www.arduino.cc/en/Reference/For

for (int i = 0; i < 4; i++) {
  thumb.write(0);
  delay(20);
  thumb.write(0);
  index.write(0);
  middle.write(0);
  ring.write(0);
  pinky.write(0);

  thumb.write(150);
  index.write(150);
  middle.write(150);
  ring.write(150);
  pinky.write(150);
}