Switch Interfacing with Arduino  

What is a Switch?

A switch is an electrical device used to control the flow of current in a circuit. It works by opening (breaking) or closing (completing) an electrical path. Switches are commonly used as input devices in Raspberry Pi projects to control LEDs, motors, and other electronic components.

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. GPIO.input()

Reads the current state of a GPIO pin.

Syntax

GPIO.input(pin)

Parameters

  • pin: GPIO pin number connected to the switch.

Returns

  • GPIO.HIGH (1) – Switch not pressed (depending on circuit configuration)
  • GPIO.LOW (0) – Switch pressed

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

 Code:-

import RPi.GPIO as GPIO

import time


LED = 18

SW = 23


GPIO.setmode(GPIO.BCM)

GPIO.setup(LED, GPIO.OUT)

GPIO.setup(SW, GPIO.IN, pull_up_down=GPIO.PUD_UP)


while True:

    if GPIO.input(SW) == GPIO.LOW:

        GPIO.output(LED, GPIO.HIGH)

    else:

        GPIO.output(LED, GPIO.LOW)

Output:-



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

Code:-

import RPi.GPIO as GPIO

import time


LED = 18

SW1 = 23

SW2 = 24


GPIO.setmode(GPIO.BCM)


GPIO.setup(LED, GPIO.OUT)

GPIO.setup(SW1, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.setup(SW2, GPIO.IN, pull_up_down=GPIO.PUD_UP)


while True:

    if GPIO.input(SW1) == GPIO.LOW:

        GPIO.output(LED, GPIO.HIGH)


    elif GPIO.input(SW2) == GPIO.LOW:

        GPIO.output(LED, GPIO.LOW)

Output:-



Task 3:- WAP to blink an LED.

Code:-


import RPi.GPIO as GPIO

import time


LED = 18

SW = 23


GPIO.setmode(GPIO.BCM)


GPIO.setup(LED, GPIO.OUT)

GPIO.setup(SW, GPIO.IN,)


while True:

    if GPIO.input(SW) == GPIO.LOW:

        GPIO.output(LED, GPIO.HIGH)

        time.sleep(1)


        GPIO.output(LED, GPIO.LOW)

        time.sleep(1)

Output:-