Introduction: Arduino: Control Multiple Components W/ One Button

About: I am here to share what I make. Hopefully, you can learn from watching what I have done and even improve upon it. As an Amazon Associate I earn from qualifying purchases.

This is a circuit that allows you toggle between three different components, in this case LEDs, by pressing a button. The cycle advances each time you press the button: (1) turns all off, (2) turn red on, (3) turn yellow on & red off, (4) turn green on &yellow off, (1) turns all off again, and repeats.

Please note that I have entered this instructable into the ROBOTICS contest, so please vote for it!

Step 1: Acquire Parts

You will need:

> a push button

>1kΩ resistor (brown-black-red)

>3 elements to control (I'm using LEDs)

>3 220Ω resistors (red-red-brown)*

*Only if you are using LEDs as your elements to control

Step 2: Put Parts on the Board

Just follow the picture!

Step 3: Wiring

Wire as follows: (or look at the picture)

>Pushbutton goes to 5v, and digital pin 2 and ground through a 1kΩ resistor

>Component 1 goes to digital pin 5, and ground

>Component 2 goes to digital pin 7, and ground

>Component 3 goes to digital pin 9, and ground

Step 4: Upload Your Code!

Here is the code:

int switchPin = 2;
int led1Pin = 7;
int led2pin = 9;
int led3pin = 5;
int val;
int val2;
int buttonState;
int Mode = 0;
void setup() {
  pinMode(switchPin, INPUT);
  pinMode(led1Pin, OUTPUT);
  pinMode(led2pin, OUTPUT);
  pinMode(led3pin, OUTPUT);
  buttonState = digitalRead(switchPin);
}
void loop() {
  val = digitalRead(switchPin);
  delay(10);
  val2 = digitalRead(switchPin);
  if (val == val2) {
    if (val != buttonState) {
      if (val == LOW) {
        if (Mode == 0) {
          Mode = 1;
        } else {
          if (Mode == 1) {
            Mode = 2;
          } else {
            if (Mode == 2) {
              Mode = 3;
            } else {
              if (Mode == 3) {
                Mode = 0;
              }
            }
          }
        }
      }
    }
    buttonState = val;
  }
  if (Mode == 0) { // all-off
    digitalWrite(led1Pin, LOW);
    digitalWrite(led2pin, LOW);
    digitalWrite(led3pin, LOW);
  }
  if (Mode == 1) {
    digitalWrite(led1Pin, HIGH);
    digitalWrite(led2pin, LOW);
    digitalWrite(led3pin, LOW);
  }
  if (Mode == 2) {
    digitalWrite(led1Pin, LOW);
    digitalWrite(led2pin, HIGH);
    digitalWrite(led3pin, LOW);
  }
  if (Mode == 3) {
    digitalWrite(led1Pin, LOW);
    digitalWrite(led2pin, LOW);
    digitalWrite(led3pin, HIGH);
  }
}


This code was made byThat1guy99* and tweaked by me.

*See it here: http://forum.arduino.cc/index.php?topic=124707.0

Robotics Contest 2016

Participated in the
Robotics Contest 2016