To understand more about Array, on the Sketch program under a simpler version than the previous Sketch by utilizing a FOR loop and Array.
// www.ioisalman.com // Initialization Number of LEDs const int numLED = 4; // LED 1,2,3, & 4 so one variable // the index address 0,1,2,3 const int pinLED[numLED] = {8,9,10,11}; void setup() { // Initialize all LED pins as OUTPUT for(int i=0; i<4; i++) { pinMode(pinLED[i], OUTPUT); } } void loop() { // Turn off all LED for(int i=0; i<4; i++) { digitalWrite(pinLED[i], LOW); } delay(1000); // Turn on all LEDs gradually dg 1 second pause for(int i=0; i<4; i++){ digitalWrite(pinLED[i], HIGH); delay(1000); } }
When compared with the previous Sketch without the description line comment, the Sketch on top is much shorter and more simple.
In Sketch above, the four LEDs contained in one variable is the variable Array pinLED. Each LED can be accessed by index address. Notice in line 9
const int pinLED[numLED] = {8,9,10,11};
Automatically, the index address for each LED depends on the sequence of the pin. Pin 8 is on ke0 index address, pin 9 is in the index to 1, the pin 10 is in the index to 2, and pin 11 is in the index to 3. So to access the pin 8, we can add the brackets and address of the index-0 , as follows:
Pin8 = pinLED[0]
for(int i=0; i<4; i++){
Yep, I hope the above explanation Array easily understood. If there is any confusion, please ask questions on the website, the author will gladly answer. Good, then we will further develop Sketch on top of that a little more complex and more interesting the animation. The author provides Sketch Sketch 2.8 and 2.9 to be analyzed and studied:
Sketch 2.8
// Initialize Number of LEDs const int numLED = 4; // LED 1,2,3, & 4 so one variable // The index address 0,1,2,3 const int pinLED [numLED] = {8,9,10,11}; void setup () { // Initialize all LED pins as OUTPUT for (int i = 0; i <4; i ++) { pinMode (pinLED [i], OUTPUT); } } void loop () { // Turn on all LEDs gradually dg 1 second pause for (int i = 0; i <4; i ++) { digitalWrite (pinLED [i], HIGH); delay (500); } // off all LEDs gradually dg 1 second pause for (int i = 0; i <4; i ++) { digitalWrite (pinLED [i], LOW); delay (500); } }
Sketch 2.9
// Initialize Number of LEDs const int numLED = 4; // LED 1,2,3, & 4 so one variable // Dengaan index address 0,1,2,3 const int pinLED [numLED] = {8,9,10,11}; void setup () { // Initialize all LED pins as OUTPUT for (int i = 0; i <4; i ++) { pinMode (pinLED [i], OUTPUT); } } void loop () { // Turn led an index of 0 to 2 one by one for (int i = 0; i <3; i ++) { digitalWrite (pinLED [i], HIGH); delay (200); digitalWrite (pinLED [i], LOW); } // Turn led the index 3 to 1 one by one for (int i = 3; i> 0; i -) { digitalWrite (pinLED [i], HIGH); delay (200); digitalWrite (pinLED [i], LOW); } }
0 Response to "The introduction of Array in arduino"
Post a Comment