Programming Examples

Write a program to interface four LEDs (pins 10, 11, 12, 13) and a push button (pin 2) to toggle the LED states as follows:


Write a program to interface four LEDs (pins 10, 11, 12, 13) and a push button (pin 2) to toggle the LED states as follows: first press: Blink all LEDs simultaneously (1 sec delay), second press: Turn off all LEDs, third press: Blink LEDs alternatively (even first, then odd; 0.5 sec delay), repeat the sequence on subsequent presses.

Solution

int mode = 0;
void setup()
{
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(2, INPUT);
  Serial.begin(9600);
}

void loop()
{
  int btnValue = digitalRead(2);

  // Detect button press
  if (btnValue == HIGH )
  {
    mode=mode+1;
    if(mode>3)
      mode=1;
	Serial.println("Button Pressed");
    delay(1000);    // Debounce
  }
  Serial.println(mode);
  if(mode==1)
  {
      digitalWrite(10, HIGH);
      digitalWrite(11, HIGH);
      digitalWrite(12, HIGH);
      digitalWrite(13, HIGH);
      delay(1000);

      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      digitalWrite(12, LOW);
      digitalWrite(13, LOW);
      delay(1000);
  }
  else if(mode==2)
  {

    // Second Press: Turn OFF all LEDs

      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      digitalWrite(12, LOW);
      digitalWrite(13, LOW);    
    
  }
  else if(mode==3)
  {

    // Third Press: Alternate blinking
    
      // Even LEDs (10 & 12)
      digitalWrite(10, HIGH);
      digitalWrite(12, HIGH);
      digitalWrite(11, LOW);
      digitalWrite(13, LOW);
      delay(500);

      // Odd LEDs (11 & 13)
      digitalWrite(10, LOW);
      digitalWrite(12, LOW);
      digitalWrite(11, HIGH);
      digitalWrite(13, HIGH);
      delay(500);
  }
 
}
Output


Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad