...

Instruction

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

My Assignment

Detail image

Code

Version-1

/*
'both off, LED1 on, both on' in a loop.
- Yihan1023
*/
int buttonState = 0;
int tim = 100;
int count = 1;

void setup() {
  // put your setup code here, to run once:
  pinMode(2,INPUT);//button
  pinMode(9,OUTPUT);//LED1
  pinMode(10,OUTPUT);//LED2

}

void loop() {
  // put your main code here, to run repeatedly:
  buttonState = digitalRead(2);
  if(buttonState == HIGH){
    count += 1;
    delay(tim);
  }
  //both off
  if(count % 3 == 1){
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    delay(tim);
  }
  //LED1 on
  if(count % 3 == 2){
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    delay(tim);
  }
  //both on
  if(count % 3 == 0){
    digitalWrite(9,HIGH);
    digitalWrite(10,HIGH);
    delay(tim);
  }
}

Version-2

/*
'both off, LED1 on, both on' in a loop. Long-press won't change.
- Yihan1023
*/

int buttonState = 0;
int tim = 100;
int count = 1;
bool press = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(2,INPUT);//button
  pinMode(9,OUTPUT);//LED1
  pinMode(10,OUTPUT);//LED2

}

void loop() {
  // put your main code here, to run repeatedly:
  buttonState = digitalRead(2);
  if(buttonState == HIGH && press == false){
    count += 1;
    delay(tim);
    press = true;
  }
  if(buttonState == LOW){
    press = false;
  }
  //both off
  if(count % 3 == 1){
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    delay(tim);
  }
  //LED1 on
  if(count % 3 == 2){
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    delay(tim);
  }
  //both on
  if(count % 3 == 0){
    digitalWrite(9,HIGH);
    digitalWrite(10,HIGH);
    delay(tim);
  }
}

Video