Arrays

# プログラム

## 定義等

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 `````` ``````/* Arrays Demonstrates the use of an array to hold pin numbers in order to iterate over the pins in a sequence. Lights multiple LEDs in sequence, then in reverse. Unlike the For Loop tutorial, where the pins have to be contiguous, here the pins can be in any random order. 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/Arrays */ int timer = 100; // The higher the number, the slower the timing. int ledPins[] = { 2, 7, 4, 6, 5, 3 }; // an array of pin numbers to which LEDs are attached int pinCount = 6; // the number of pins (i.e. the length of the array) ``````
 ``````33 34 35 36 37 `````` ``````// first visible ASCIIcharacter '!' is number 33: int thisByte = 33; // you can also write ASCII characters in single quotes. // for example, '!' is the same as 33, so you could also use this: // int thisByte = '!'; ``````

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

また、int型の配列ledPins[]を定義し、初期化します。この例ように配列の要素数を記述せずに初期化することができます。

## setup()

 ``````29 30 31 32 33 34 35 36 `````` ``````void setup() { // the array elements are numbered from 0 to (pinCount - 1). // use a for loop to initialize each pin as an output: for (int thisPin = 0; thisPin < pinCount; thisPin++) { pinMode(ledPins[thisPin], OUTPUT); } } ``````

for文を使いthisPinを0からpinCount-1(=5)まで変化させます。pinMode()でledPin[thisPin]を出力モードにします。

ledPin[]は以下のようになっているので、結果として、2、7、4、6、5、3の順に初期化されます。

thisPin ledPin[thisPin]
0 2
1 7
2 4
3 6
4 5
5 3

## loop()

 ``````37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 `````` ``````void loop() { // loop from the lowest pin to the highest: for (int thisPin = 0; thisPin < pinCount; thisPin++) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); } // loop from the highest pin to the lowest: for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) { // turn the pin on: digitalWrite(ledPins[thisPin], HIGH); delay(timer); // turn the pin off: digitalWrite(ledPins[thisPin], LOW); } }``````

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

# バージョン

 Hardware: Arduino UNO R3 Software: Arduino 1.8.16

November 1, 2022