...

Assignment

Description

Create a circuit and Arduino code that does the following

Circuit

  • Connect two LEDs to your Arduino using a breadboard
  • Connect one switch to your Arduino using a breadboard

Code

  1. Read a momentary switch being pressed
  2. When the program starts, both LEDs are off
  3. When the switch is pressed once, the first LED turns on
  4. When the switch is pressed the second time, the second LED turns on (the first one should also still be on)
  5. When the switch is pressed the third time, both LEDs turn off
  6. Repeat this same cycle of LEDs turning on and off in sequence (off, one LED, two LEDs, off…)

Solution

I built the circuit and developed the logic with Arduino IDE. See the demo video, images and code below.

Video

Images

Detail image Photo of the completed circuit.

Code

int led1Pin = 9;
int led2Pin = 10;
int inPin = 12;
int pressCounter = 0;

void setup() {
  // Initialize the two LEDs and button
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(inPin, INPUT);
}

void loop() {
  // Read button value
  if (digitalRead(inPin) == HIGH) {
    pressCounter++;
  }

  // Check the state, turn on/off LEDs
  if ((pressCounter % 3) == 1) {
    digitalWrite(led1Pin, HIGH);
  } else if ((pressCounter % 3) == 2) {
    digitalWrite(led2Pin, HIGH);
  } else {
    digitalWrite(led1Pin, LOW);
    digitalWrite(led2Pin, LOW);
  }

  // Delay to avoid multiple button reads on single press
  delay(300);
}