...

Assignment

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…)

Images

Some pictures of my work: Detail image Detail image

Code

My code:

int btnPin = 2;
int ledPin1 = 9;//LED 1
int ledPin2 = 10;//LED 2

int btnState = 0;
int prevBtnState = 0;
int counter = 0;

void setup() {
  // Open the serial port
  Serial.begin(9600);
  // set the button pin to be an input
  pinMode(btnPin, INPUT);
  // set the LED pin to be an OUTPUT
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {
  // read the button pin
  btnState = digitalRead(btnPin);

  // check if the button state has changed
  if(btnState != prevBtnState){
    // print the changed state
    Serial.print("Button state changed to: ");
    Serial.println(btnState);
    prevBtnState =1;

    if (btnState == HIGH) {
      int remainder = counter % 3;
      digitalWrite(ledPin1, remainder != 0);
      digitalWrite(ledPin2, remainder > 1);
      Serial.println(remainder);
      counter++;
    }

    if (btnState == LOW) {
      prevBtnState = 0;
    }
  }
  delay(10);
  
}

Simulation of the circuit and the code on wokwi:

Video

The video of my work: