60. LED Patterns Switching

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

How do you plan to solve it?

Here I have created two different functions for both patterns. And one integer variable named as 'stat' to store the current stat of the patterns. 

digital pin 2 is selected as an Interrupt pin. When negative edge appears on the pin, the attachInterrupt function will call switch_pattern function which toggles the value of stat.

In loop function, if else condition is used to select the pattern based on available value in stat.

Code

int leds[4] = {8,9,10,11};
int stat = 0;
int but = 2;

void switch_pattern(){
  stat = !stat;
}

void pattern0(){
  digitalWrite(leds[0], HIGH);
  digitalWrite(leds[1], HIGH);
  digitalWrite(leds[2], HIGH);
  digitalWrite(leds[3], HIGH);
  delay(500);
  digitalWrite(leds[0], LOW);
  digitalWrite(leds[1], LOW);
  digitalWrite(leds[2], LOW);
  digitalWrite(leds[3], LOW);
  delay(500);
}

void pattern1(){
  digitalWrite(leds[0], HIGH);
  digitalWrite(leds[1], LOW);
  digitalWrite(leds[2], HIGH);
  digitalWrite(leds[3], LOW);
  delay(500);
  digitalWrite(leds[0], LOW);
  digitalWrite(leds[1], HIGH);
  digitalWrite(leds[2], LOW);
  digitalWrite(leds[3], HIGH);
  delay(500);
}

void setup(){
  for(int i=0; i<4;i++){
    pinMode(leds[i], OUTPUT);
  }
  pinMode(but, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(but), switch_pattern, FALLING);
}

void loop(){
  if(stat)
    pattern1();
  else
    pattern0();
}

Photo of Output

 

Was this helpful?
Upvote
Downvote