...

Assignment

The task for our first week was to create a circuit and Arduino code that does the following.

  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

Below you can find an image of the circuit and the code for Arduino.

Image

Detail image

Code

const int buttonPin = 2;
const int led1 = 9;
const int led2 = 10;

int buttonState = LOW;
int oldState = LOW; 
int currentState = 0;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read button state
  buttonState = digitalRead(buttonPin);
  delay(100); // delay for button

  if (buttonState != oldState) {
    if (buttonState == HIGH) {
      // update the currentState
      currentState = (currentState + 1) % 3;
    }
    oldState = buttonState; //update old state accordingly
  }

  // lit leds based on current state
  if (currentState == 1) {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, LOW);
  } else if (currentState == 2) {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
  } else {      
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
  }
}