Friday, July 04, 2014

LED Chase Effect using Arduino

We are now going to use a string of LEDs (10 in total) to make an LED chase effect (see Table 3-1), similar to that used
on the car KITT in the KnightriderTV series or the Cylons in Battlestar Galactica.













Connect It Up

First, make sure your Arduino is powered off by unplugging it from the USB cable. Now take your breadboard, LEDs, resistors, and wires, and connect everything up as in Figure 3-1. Check your circuit thoroughly before connecting the power back up to the Arduino.



Enter the Code
Open up your Arduino IDE and type in the code .

 LED Chase Effect

byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Create array for LED pins
int ledDelay = 65; // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
void setup() {
for (int x=0; x<10; x++)
{
// set all pins to output
pinMode(ledPin[x], OUTPUT);
}
changeTime = millis();
}
void loop() {
if ((millis() - changeTime) > ledDelay)
{
// if it has been ledDelay ms since last change
changeLED();
changeTime = millis();
}
}
void changeLED()
 {
for (int x=0; x<10; x++)
{
// turn off all LED's
digitalWrite(ledPin[x], LOW);
}
digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED
currentLED += direction; // increment by the direction value
// change direction if we reach the end
if (currentLED == 9) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}

If you have done everything
correctly, you should now see the LEDs appear to move along the line, then bounce back to the start.

By changing the value of ledDelay, you can make the LED ping back and forth at different speeds. Try different
values to see what happens. You have to stop the program and manually change the value of ledDelay, then upload the amended code to see any changes.











No comments:

Post a Comment