// ============================================
// Knight Rider LED Chaser with Speed Control
// ============================================
// Variable Declaration
int led[] = {22, 24, 26, 28, 30, 32, 34, 36}; // Array of LED pin numbers
int number_of_leds = sizeof(led)/sizeof(int); // Calculate total number of LEDs (8)
int position = 0; // Current LED position in array
int direction = 1; // Movement direction: 1 = forward, -1 = backward
int potentiometer = A0; // Potentiometer connected to analog pin A0
int potentiometer_value = 0; // Variable to store potentiometer reading
int speed = 0; // Variable to control animation speed
void setup() {
// Initialize all LED pins and test them
for(int i = 0; i < number_of_leds; i++) {
pinMode(led[i], OUTPUT); // Set each LED pin as OUTPUT
digitalWrite(led[i], HIGH); // Turn ON all LEDs for functionality test
}
delay(500); // Keep all LEDs ON for 500ms to verify connections
// Turn OFF all LEDs after test
for(int i = 0; i < number_of_leds; i++) {
digitalWrite(led[i], LOW);
}
}
// Main Program Loop
void loop() {
// Turn ON the LED at current position
digitalWrite(led[position], HIGH);
// Update position based on current direction
position += direction; // Move forward (+1) or backward (-1)
// Check if we've reached the boundaries and reverse direction
if(position == number_of_leds - 1 || position == 0) {
direction *= -1; // Reverse direction (1 becomes -1, or -1 becomes 1)
}
// Turn OFF the LED at the new position (creates chaser effect)
digitalWrite(led[position], LOW);
// Read potentiometer value (0 to 1023)
potentiometer_value = analogRead(potentiometer);
// Use potentiometer value as delay time to control speed
delay(potentiometer_value); // Higher value = slower animation
}