ForLoopIteration

# はじめに

for文の使い方を示します。

デジタルの2番ピンから7番ピンにLEDをつないでいる想定です。

# プログラム

## 定義等

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 `````` ``````/* For Loop Iteration Demonstrates the use of a for() loop. Lights multiple LEDs in sequence, then in reverse. The circuit: - LEDs from pins 2 through 7 to ground created 2006 by David A. Mellis modified 30 Aug 2011 by Tom Igoe This example code is in the public domain. https://www.arduino.cc/en/Tutorial/BuiltInExamples/ForLoopIteration */ int timer = 100; // The higher the number, the slower the timing. ``````

int型の変数timerを定義し初期化します。

## setup()

 ``````22 23 24 25 26 27 28 `````` ``````void setup() { // use a for loop to initialize each pin as an output: for (int thisPin = 2; thisPin < 8; thisPin++) { pinMode(thisPin, OUTPUT); } } ``````

for文を使いthisPinをから7まで変化させます。pinMode()でthisPinを出力モードにします。

## loop()

 ``````29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 `````` ``````void loop() { // loop from the lowest pin to the highest: for (int thisPin = 2; thisPin < 8; thisPin++) { // turn the pin on: digitalWrite(thisPin, HIGH); delay(timer); // turn the pin off: digitalWrite(thisPin, LOW); } // loop from the highest pin to the lowest: for (int thisPin = 7; thisPin >= 2; thisPin--) { // turn the pin on: digitalWrite(thisPin, HIGH); delay(timer); // turn the pin off: digitalWrite(thisPin, LOW); } }``````

2回目のfor文ではthisPinを7から2まで順に変化させ、digitalWrite()でピンを制御します。

# バージョン

 Hardware: Arduino UNO R3 Software: Arduino 1.8.16

November 1, 2022