2009-05-24

Array of Instances - Indexed Lists With Added Power

Let's see what's in the intensity filing cabinet.

Hmm, drawer 0 labeled Red contains 127, drawer 1 labeled Green contains 192 and drawer 2 labeled Blue contains 50. Send the respective value as a PWM output to each terminal on the RGB LED.

Indexed lists, commonly known as arrays are a powerful tool for arranging groups of variables. We've seen them used for organizing lists of data such as pin assignments, multiple sensor inputs and character strings. Can we do the same for objects?

Here's a sample sketch showing how to set up an "Array of Instances" and then use a for() loop to do something with that array.

We will be using the HAL LED Library to create the instances in the array, so include the library:

#include <LED.h>   // include HAL LED class

and then create the array:

//create array of LED instances
LED led[7] = {   // refer to LEDs as led[0] thru led[6]
LED(6),
LED(7),
LED(8),
LED(9),
LED(10),
LED(11),
LED(12)
};


and here's the full sketch.

Knight Rider 4
/*****************************************************************************
* Knight Rider 4
*
* @Sketch by Capt.Tagon showing use of LED class
* and an array of instances thereof.
*
* Using LED abstraction library by Alexander Brevig
* http://www.arduino.cc/playground/Code/LED
*
* @description
* Demonstrates the functionality of the LED class
*
* attributes
* .getState() returns current LED state
*
* digital methods
* .on() turns LED on
* .off() turns LED off
* .toggle() changes current LED state
*
* analog methods -> use on ATmega168 Arudino pins 3, 5, 6, 9, 10, and 11
* .setValue() sets PWM 0-255 value
* .fadeIn(millis) on PWM pin, fades in over millis time
* .fadeOut(millis) on PWM pin, fades out over millies time
*
* create array of LED instances and play Knight Rider with them
******************************************************************************/

#include <LED.h> // include HAL LED class

//create array of LED instances
LED led[7] = { // refer to LEDs as led[0] thru led[6]
LED(6),
LED(7),
LED(8),
LED(9),
LED(10),
LED(11),
LED(12)
};

byte numLeds = 7; // number of LEDs for counter
byte count; // interate through LED array
int timer = 100; // delay between steps

void setup(){
Serial.begin(9600); // Serial debugging output
}

void loop(){
for (count = 0; count < (numLeds - 1); count ++) {
Serial.println(count, DEC); // print count up
led[count].on();
delay(timer);
led[count].off();
delay(timer);
}
for (count = (numLeds - 1); count > 0; count --) {
Serial.println(count, DEC); // print count down
led[count].on();
delay(timer);
led[count].off();
delay(timer);
}
}

No comments:

Post a Comment