...

Task

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

My solution

At first, I struggled to figure out how to record a click instead of continuos press. Lu gave me a tip to count the clicks as a separate variable.

An if statement was created to count the clicks. To make it run only once when the button is pressed, I added a boolean variable (buttonState).


int button;
int clicks = 0;
bool buttonState = false;


void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(2, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  button = digitalRead(2);

  if (button == HIGH && buttonState == false) {
    clicks = clicks + 1;
    buttonState = true;
  }

  if (button == LOW) {
    buttonState = false;
  }

  if (clicks == 1) {
    digitalWrite(9, HIGH);
  }
  if (clicks == 2) {
    digitalWrite(6, HIGH);
  }
  if (clicks == 3) {
    digitalWrite(9, LOW);
    digitalWrite(6, LOW);
    clicks = 0;
  }
  
  Serial.println(clicks);
}

Alternative:

My first version of this code included delay after clicks += 1 and wrong light order (:D). I actually like the outcome of this version as continuosly pressing the button gives a nice effect.

int button;
int clicks = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(2, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  button = digitalRead(2);

  if (button == HIGH) {
    clicks = clicks + 1;
    delay(200);
  }

  if (clicks == 1) {
    digitalWrite(9, HIGH);
  }
  if (clicks == 2) {
    digitalWrite(9, LOW);
    digitalWrite(6, HIGH);
  }
  if (clicks == 3) {
    digitalWrite(9, HIGH);
  }
  if (clicks > 3) {
    clicks = 0;
    digitalWrite(9, LOW);
    digitalWrite(6, LOW);
  }
  Serial.println(clicks);
}