Added Array example, separate from for loop

This commit is contained in:
Tom Igoe 2009-07-05 19:07:27 +00:00
parent 8e10fc489c
commit 228ffc8fa7
1 changed files with 11 additions and 17 deletions

View File

@ -1,7 +1,7 @@
/* /*
For Loop Iteration For Loop Iteration
Demonstrates the use of a for() loop and arrays. Demonstrates the use of a for() loop.
Lights multiple LEDs in sequence, then in reverse. Lights multiple LEDs in sequence, then in reverse.
The circuit: The circuit:
@ -9,43 +9,37 @@
created 2006 created 2006
by David A. Mellis by David A. Mellis
modified 17 Jan 2009 modified 5 Jul 2009
by Tom Igoe by Tom Igoe
http://www.arduino.cc/en/Tutorial/Loop http://www.arduino.cc/en/Tutorial/ForLoop
*/ */
int timer = 100; // The higher the number, the slower the timing. int timer = 100; // The higher the number, the slower the timing.
int ledPins[] = {
2, 3, 4, 5, 6, 7 }; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
void setup() { void setup() {
int thisPin;
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output: // use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < thisPin; thisPin++) { for (int thisPin = 2; thisPin < 8; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT); pinMode(thisPin, OUTPUT);
} }
} }
void loop() { void loop() {
// loop from the lowest pin to the highest: // loop from the lowest pin to the highest:
for (int thisPin = 0; i < pinCount; thisPin++) { for (int thisPin = 0; i < 8; thisPin++) {
// turn the pin on: // turn the pin on:
digitalWrite(ledPins[thisPin], HIGH); digitalWrite(thisPin, HIGH);
delay(timer); delay(timer);
// turn the pin off: // turn the pin off:
digitalWrite(ledPins[thisPin], LOW); digitalWrite(thisPin, LOW);
} }
// loop from the highest pin to the lowest: // loop from the highest pin to the lowest:
for (thisPin = pinCount - 1; thisPin >= 0; thisPin--) { for (thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on: // turn the pin on:
digitalWrite(ledPins[thisPin], HIGH); digitalWrite(thisPin, HIGH);
delay(timer); delay(timer);
// turn the pin off: // turn the pin off:
digitalWrite(ledPins[thisPin], LOW); digitalWrite(thisPin, LOW);
} }
} }