Saturday, August 5, 2017

Knight Rider (Using Array)

Knight Rider (Array)

Using the "Brute Force" for the Knight Rider program we found ourselves repeating the same commands over and over again while only changing the pin number with each program step. With the code below we will create and use an array named Led[] to cycle through each LED. Incrementing the index variable for the array changes each LED pin number programatically instead of creating a large amount of unnecessary code. By using a array to cycle through pins the code we use is drastically reduced.


Hookup for Knight Rider Using Array

NOTE: Leds should be installed with short leads negative.

//--------------------------- Copy Code Below ------------

int dT = 50; //Global Variable
int Led[] = {13,12,11,10,9,8}; //An array of pin numbers. First element of the array (element 0) is on the left of the array

void setup()
{
  pinMode(13, OUTPUT); //All pins involved need to be designated as outputs
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop()
{

for (int x = 0; x <= 5; x++) //Blink to the right from pin 13 to pin 8 (counting up)
{
  digitalWrite(Led[x], HIGH); // Turn ON current LED
  digitalWrite(Led[x-1], LOW); //Turn OFF prior LED
  delay(dT);
}

for (int x = 5; x >=0; x--) //Blink to the left from pin 8 to pin 13 (counting down)
{
  digitalWrite(Led[x], HIGH); //Turn ON current LED
  digitalWrite(Led[x+1], LOW); //Turn OFF prior LED
  delay(dT);
}

}

//--------------------------- End of code -------------

No comments:

Post a Comment