Using Switch with Raspberry Pi – Python

Push Button Switch

Using Switch with Raspberry Pi – Python

I hope that you already go through our tutorial, LED Blinking using Raspberry Pi. Detecting switch status is one of the basic step in learning Raspberry Pi GPIO operations. Here we using Python programming language.

I hope that you already installed Python GPIO Library in your Raspberry Pi, if not please follow our first tutorial LED Blinking using Raspberry Pi.

Raspberry Pi GPIO Pin Out

Raspberry Pi GPIO layout

Raspberry Pi GPIO layout

Pull Up and Pull Down

Raspberry Pi has internal Pull Up and Pull Down resistors which can be enabled through software. Alternately external pull up and pull down resistors may also be used. Here we use Internal Pull Up Resistors.

Pull up resistors give a default HIGH state to input pin while pull down resistors a default LOW state. If no pull resistor is added to an input pin, it remains floating. Any wire connected to that pin can act as an antenna and can build up stray voltages. Pull resistors can avoid such discrepancies and provide a smooth operation.


PULL-UP and PULL-DOWN Resistors

PULL-UP and PULL-DOWN Resistors

The GPIO ports consist of software configurable internal pull up and pull down resistors. Pull up resistors have a value between 50KΩ ~ 65KΩ and pull down resistors between 50KΩ ~ 60KΩ. You should use following commands to configure it. 

Pull Down

GPIO.setup(port_or_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

Pull Up

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

Circuit Diagram

Connect the push button switch to 6 (ground) and 12 (GPIO).

Circuit diagram button press

Circuit diagram button press

Python Programming

  • Open terminal.
  • Launch IDLE IDE by typing the following command.
sudo idle

This launches IDLE with superuser privileges which are essential for executing GPIO scripts.

  • After IDLE launches, open a new window

Type the code below in the window.



import RPi.GPIO as GPIO          #Import GPIO library
import time                      #Import time library
GPIO.setmode(GPIO.BOARD)         #Set GPIO pin numbering
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Enable input and pull up resistors
while True:
    input_state = GPIO.input(12) #Read and store value of input to a variable
    if input_state == False:     #Check whether pin is grounded
       print('Button Pressed')   #Print 'Button Pressed'
       time.sleep(0.3)           #Delay of 0.3s
  • Save the code
  • Run your code
Output button press

Output button press

The program will print “Button Pressed” message when the push button switch is pressed. The time.sleep(0.3) command will provide necessary delay between switch press. If it is not used, the program will print multiple “Button Pressed” message with one single press. Hope you understand the tutorial. If you have any doubts, please comment below.

Share this post