Connect two LEDs to your Arduino using a breadboard
Connect one switch to your Arduino using a breadboard
Code
Read a momentary switch being pressed
When the program starts, both LEDs are off
When the switch is pressed once, the first LED turns on
When the switch is pressed the second time, the second LED turns on (the first one should also still be on)
When the switch is pressed the third time, both LEDs turn off
Repeat this same cycle of LEDs turning on and off in sequence (off, one LED, two LEDs, off…)
My Assignment
Code
Version-1
/*
'both off, LED1 on, both on' in a loop.
- Yihan1023
*/int buttonState =0;
int tim =100;
int count =1;
voidsetup() {
// put your setup code here, to run once:
pinMode(2,INPUT);//button
pinMode(9,OUTPUT);//LED1
pinMode(10,OUTPUT);//LED2
}
voidloop() {
// 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;
voidsetup() {
// put your setup code here, to run once:
pinMode(2,INPUT);//button
pinMode(9,OUTPUT);//LED1
pinMode(10,OUTPUT);//LED2
}
voidloop() {
// 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);
}
}