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
- 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…)
Solution
I built the circuit and developed the logic with Arduino IDE. See the demo video, images and code below.
Video
Images
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);
}