Raspberry Pi Beginners Tutorial 3: Creating a Switch Circuit

You can also use the GPIO pins as inputs to detect sensors and switches.

The GPIO pins can also be used to detect input signals and can therefore be linked to switch circuits.

Set up the following circuit using the push button switches. Take care to note which way the switches are inserted. Also make sure that the legs off the components are not touching.

Raspberry Pi Switch Circuit Schematic Wiring Diagram

Open IDLE on your Raspberry Pi (Menu > Programming > Python 2 (IDLE)) and open a new project (File > New File).  Then type the following:

import RPi.GPIO as GPIO
import time


GPIO.setup(SwitchA, GPIO.IN)
GPIO.setup(SwitchB, GPIO.IN)
GPIO.setup(SwitchC, GPIO.IN)

while True:
    if GPIO.input(SwitchA)==True:
        print("You are pressing button A")
    if GPIO.input(SwitchB)==True:
        print("You are pressing button B")
        GPIO.output(LED, True)
    if GPIO.input(SwitchC)==True:
        print("You are pressing button C")
        GPIO.output(LED, False)

Save your project as buttons.py (File > Save As) in your Documents folder.

Now open Terminal (Menu > Accessories > Terminal) and type the following command:

python buttons.py

When you press the first button, the message "You are pressing button A" will be repeated until you stop pressing the button.

When you press the second button, a similar message will appear and the LED will light up.

When you press the third button, a similar message will appear and the LED will switch back off.

You can stop this program from running by pressing CTRL+Z.

Lines 11-13 set up the GPIO pins as input pins by using the GPIO.setup command. The script then uses the GPIO.input command to detect whether the pin is True (when a +3.3v supply is connected) or False (when the pin is connected to Ground).

To ensure that the Raspberry Pi is constantly checking the state of the pins, the script uses a loop to repeatedly run the same section of script. This is done using the while True: command on line 17. This command will then repeat any of the following lines that are indented.

The while command can also be used with a conditional statement. By changing line 17 to the following, the program will stop running when the third button is pressed:

while GPIO.input(SwitchC)==False: