CodeHub
HomeUploadContact
Back to Hub

Button controlled leds

April 1, 2026 Watch Tutorial

Wiring Schematic

Button controlled leds wiring diagram

Hardware Required

  • Arduino Board
    Buy on Amazon

Source Code

Arduino / C++
1// Define LED pins
2const int ledPins[] = {8, 9, 10, 11, 12};
3const int numLeds = 5;
4
5// Define Button pins
6const int button1 = 2;
7const int button2 = 3;
8const int button3 = 4;
9
10void setup() {
11  // Set LED pins as outputs
12  for (int i = 0; i < numLeds; i++) {
13    pinMode(ledPins[i], OUTPUT);
14  }
15
16  // Set Button pins as inputs with internal pull-up resistors
17  pinMode(button1, INPUT_PULLUP);
18  pinMode(button2, INPUT_PULLUP);
19  pinMode(button3, INPUT_PULLUP);
20}
21
22void loop() {
23  // Read the state of the buttons
24  // Note: LOW means pressed because of INPUT_PULLUP
25  if (digitalRead(button1) == LOW) {
26    pattern1();
27  } 
28  else if (digitalRead(button2) == LOW) {
29    pattern2();
30  } 
31  else if (digitalRead(button3) == LOW) {
32    pattern3();
33  }
34  else {
35    // If no button is pressed, turn all LEDs off
36    turnAllOff();
37  }
38}
39
40// --- Pattern 1: Chaser (Left to Right) ---
41void pattern1() {
42  for (int i = 0; i < numLeds; i++) {
43    digitalWrite(ledPins[i], HIGH);
44    delay(100);
45    digitalWrite(ledPins[i], LOW);
46  }
47}
48
49// --- Pattern 2: Blink All ---
50void pattern2() {
51  for (int i = 0; i < numLeds; i++) {
52    digitalWrite(ledPins[i], HIGH);
53  }
54  delay(200);
55  turnAllOff();
56  delay(200);
57}
58
59// --- Pattern 3: Alternating (Odds and Evens) ---
60void pattern3() {
61  // Turn on 1st, 3rd, 5th
62  digitalWrite(ledPins[0], HIGH);
63  digitalWrite(ledPins[2], HIGH);
64  digitalWrite(ledPins[4], HIGH);
65  digitalWrite(ledPins[1], LOW);
66  digitalWrite(ledPins[3], LOW);
67  delay(200);
68  
69  // Turn on 2nd, 4th
70  digitalWrite(ledPins[0], LOW);
71  digitalWrite(ledPins[2], LOW);
72  digitalWrite(ledPins[4], LOW);
73  digitalWrite(ledPins[1], HIGH);
74  digitalWrite(ledPins[3], HIGH);
75  delay(200);
76}
77
78// Helper function to turn all LEDs off
79void turnAllOff() {
80  for (int i = 0; i < numLeds; i++) {
81    digitalWrite(ledPins[i], LOW);
82  }
83}
5 Led
Buy on Amazon
  • 3 Button
    Buy on Amazon
  • Jumper Wires
    Buy on Amazon
  • USB Cable
    Buy on Amazon