Switch Interfacing with Arduino 

What is a Switch?

A switch is a device or component used to control the flow of electricity in a circuit. It works by opening (breaking) or closing (completing) an electric path. 

Push Button:-

Push buttons or switches connect two points in a circuit when you press them, and when the push button is open (not pressed), there is no connection between the two legs of the button.

Image And Symbol of Switch:-

Functions for switch interfacing:-

1. digitalRead( ):- Reads the value from a specified digital pin, either HIGH or LOW.

Syntax:- digitalRead(pin);

Parameters:-

pin:- To which the object is connected on the Arduino Board.

value:- HIGH or LOW

Task 1:- Turn on the LED when the switch is pressed.

 Code:-

int led=13,sw=12;

void setup()

{

  pinMode(led, OUTPUT);

  pinMode(sw, INPUT);

}


void loop()

{

  if (digitalRead(sw)== LOW)

  {

  digitalWrite(led, HIGH);

  }

Output:-

Task 2:- Turn on the LED when switch 1 is pressed and turn it off when switch 2 is pressed.

 Code:-

int led=13,sw=12,sw1=11;

void setup()

{

  pinMode(led, OUTPUT);

  pinMode(sw, INPUT);

  pinMode(sw1, INPUT);

}


void loop()

{

  if (digitalRead(sw)== LOW)

  {

  digitalWrite(led, HIGH);

  }

  else if (digitalRead(sw1)==LOW)

  {

    digitalWrite(led,LOW);

  }


Output:-


Task 3:- WAP to blink an LED.

 Code:-

int led=13,sw=12;

void setup()

{

  pinMode(led, OUTPUT);

  pinMode(sw, INPUT);

}


void loop()

{

  if (digitalRead(sw)== LOW)

  {

  digitalWrite(led, HIGH);

    delay(1000);

    digitalWrite(led,LOW);

    delay(1000);

    digitalWrite(led, HIGH);

    delay(1000);

    digitalWrite(led,LOW);

    delay(1000);

  }

 } 

Output:-