Sunday, July 31, 2011

LED Bounce Off Centre effect on Arduino UNO

One of the additional exercises in the manual was to add codes so that the LED blinkings appear to bounce off each other in the middle. The original project (Project 6) was to make an LED chase effect where the LEDs blink one at a time in sequence from one end to the other, and back the opposite direction.

The picture of circuit:

IMG_20110731_000433

The code in its entirety:

byte ledPin[] = {7, 8, 9, 10, 11, 12, 13};
int ledDelay;
int Direction1 = 1;
int Direction2 = -1;
int currentLED = 0;
int lastLED = 6;
unsigned long changeTime;
int x;
int potPin = 2;

void setup(){
  for(int x=0; x<7; x++){
    pinMode(ledPin[x], OUTPUT);
    pinMode(ledPin[6-x], OUTPUT); }
    changeTime = millis();
}

void loop(){
  ledDelay = analogRead(potPin);
  if ((millis() - changeTime) > ledDelay) {
    changeLED();
    changeTime = millis();
  }
}

void changeLED(){
  for (int x=0; x<7; x++){
    digitalWrite(ledPin[x], LOW);
    digitalWrite(ledPin[6-x], LOW);
  }
  digitalWrite(ledPin[currentLED], HIGH);
  digitalWrite(ledPin[lastLED], HIGH);
  currentLED += Direction1;
  lastLED +=Direction2;
  if (currentLED == 3){Direction1 = -1;}
  if (currentLED == 0) {Direction1 = 1;}
  if (lastLED == 6){Direction2 = -1;}
  if (lastLED == 3){Direction2 = 1;}
}

Basically what I did was I added another integer variable, lastLED and made it a 2nd output, since there will be 2 separate blinkings at one time. I duplicate whatever the code there is for currentLED for lastLED. Also added a second direction variable so that the new blinking can have an opposite direction to the first blinking. Made them start at different ends but end in the middle. I maintained the potentiometer-controlled ledDelay variable.

Not too bad for a total noob eh?

No comments: