Lesson 2 – Controlling LED with a Switch

Booting up the Raspberry Pi

  1. This section assumes that you have read through “Lesson 0 – Setup” and have a working Raspberry Pi you can connect to remotely using SSH or VNC.
  2. If that’s not the case please head back to “Lesson 0 – Setup” and work through the instructions provided.
  3. Let’s now get started and boot up the Raspberry Pi.
  4. Grab a good quality USB cable and a USB power adaptor (2.5A).
  5. Plug one end of the USB cable into the plug and the other microUSB end into the Raspberry Pi.
  6. This should now power up the Raspberry Pi.
  7. Once the Raspberry Pi has booted up, please ensure that it is able to connect it to the network so that you can access it over VNC.
  8. If you are using a local monitor connected to the Raspberry Pi, you are all sorted.
  9. Else get connected to the Raspberry Pi using VNC.

Important Concepts

01 / What is a button or a switch – An electrical switch is a device used to interrupt the flow of electrons in a circuit. Switches are essentially binary devices: they are either completely on (“closed”) or completely off (“open”). There are many different types of switches and the ones we will be using on our circuit is a simple push button switch. Here’s what a push button switch might look like.

Here’s how switches might be represented in an electronic circuit.

   Or    

Let’s get started

  1. Our next tutorial is called, “Controlling an LED using a Switch”.
  2. We will start off this tutorial by first putting together the circuit using a breadboard.
  3. We will wire up an LED, connect it up to the Raspberry Pi through a 220 Ohm resistor, connect the switch, power it up and write some python code.

We use a resistor to limit the current flowing through the LED. In this lesson, we will learn how to program Raspberry Pi to make an LED blink when a button press is detected. Now, let’s get started. Components required for this tutorial include –

  1. 1 Raspberry Pi
  2. 1 Breadboard
  3. 1 Raspberry Pi Cobbler / T-Extension Board
  4. 1 40-Pin Cable to connect the Raspberry Pi Cobbler / T-Extension Board to the Raspberry Pi
  5. 1 LED
  6. 1 Resistor (220Ω)
  7. 1 Push button switch
  8. Dupont jumper wires

Lets wire up your circuit based on the fritzing diagram below.

PLEASE NOTEPlease make sure you have disconnected your breadboard from the Raspberry Pi before commencing build of the circuit. Once you have put the circuit together, get someone around you to review the circuit and confirm that the connections are proper before you proceed and power up the breadboard.

Wiring up

In this experiment, we have connected a 220Ω resistor to the anode (the longer leg of the LED is the Anode and the shorter leg of the LED is the Cathode), followed by the other end of the resistor to our 3.3 V power source on the breadboard (using the Raspberry Pi Cobbler / T-Extension Board) and finally connected the connect the cathode (the shorter leg) of the LED to B17 of Raspberry Pi. The fritzing diagram below provides a view of all of the connections that need to be made for this tutorial.

 

To summarize our connections look like the following –

  1. Setup the Raspberry Pi Cobbler / T-Extension Board on the Breadboard.
    1. See the fritzing diagram below to understand what a suitable setup might look like.
    2. Note that one pair of the Ground/3.3V connects to the upper two (horizontally connected) rows of the breadboard.
    3. The second pair of the Ground/5V connects to the lower two (horizontally connected) rows of the breadboard.
  2. Wire up the 220Ω resistor to the anode (the longer leg of the LED is the Anode and the shorter leg of the LED is the Cathode)
  3. Wire up the other end of the resistor to our 3.3 V power source on the breadboard (using the Raspberry Pi Cobbler / T-Extension Board)
  4. Wire up the cathode (the shorter leg) of the LED to B17 of Raspberry Pi.
  5. Connect one terminal of the button to the B18 pin of the breadboard using the Raspberry Pi Cobbler / T-Extension Board.
    1. See the fritzing diagram to understand which terminals of the push button switch are used
    2. Generally you will use two diagonally opposite ends of the push button switch and connect them.
    3. One end goes to ground and the other end of the push button switch goes to the Raspberry Pi, in our case pin B18

How Does It Work

We can see from the first schematic diagram below that the Anode of the LED connects to a 220 Ohm current-limiting resistor and then to 3.3V power source (on the Raspberry Pi using the Raspberry Pi Cobbler / T-Extension Board). Therefore, to turn on an LED, we need to program the B17 pin on the Raspberry Pi to be low (0 Volt). This can be achieved using a few different programming languages but in our case we will be using Python.

The second schematic diagram below shows the two diagonally opposite ends of the push button switch connected to ground and the B18 pin on the Raspberry Pi (through the T-Extension Board). In this tutorial we extend the code from the previous tutorial and detect a button press before triggering the LED on/off. Switches are a common component used to control electronic devices. They are usually used to connect or disconnect circuits. Although switches come in a variety of sizes and shapes, the one used here is a 6mm mini-button as shown in the following pictures. Pin 1 is connected to pin 2 and pin 3 to pin 4. So you just need to connect either pin 1 or pin 2 to either pin 3 or pin 4.

The switch we are using is a normally open switch (i.e. your circuit is normally off/closed as the button is in the open position) as the input for the Raspberry Pi. When the button is pressed, the 4 pins are connected, thus closing the circuit. In this example when the button is pressed, the B18 pin will turn low (0V) since pin B18 on the Raspberry Pi is now connected to Ground. We will then write code to detect the (low) state of the pin and light up the LED.

Here’s what the real world project will look like once you have wired up all the relevant components i.e. Raspberry Pi 3B+, Raspberry Pi Cobbler / T-Extension Board, breadboard, 220 Ohm resistor, Push button switch and an LED.

Let’s Write Some Python Code

Open up the Thonny editor on your Raspberry Pi and let’s start putting together some code……

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
# Set #17 as LED pin
LedPin = 17
# Set #18 as button pin
BtnPin = 18
# Set Led status to True(OFF)
Led_status = True
# Define a function to print message at the beginning
def print_message():
	print ("========================================")
	print ("|          Button control LED          |")
	print ("|    ------------------------------    |")
	print ("|         LED connect to GPIO0         |")
	print ("|        Button connect to GPIO1       |")
	print ("|                                      |")
	print ("|   Press button to turn on/off LED.   |")
	print ("|                                      |")
	print ("|                            SunFounder|")
	print ("========================================\n")
	print 'Program is running...'
	print 'Please press Ctrl+C to end the program...'
	raw_input ("Press Enter to begin\n")
# Define a setup function for some setup
def setup():
	# Set the GPIO modes to BCM Numbering
	GPIO.setmode(GPIO.BCM)
	# Set LedPin's mode to output, 
	# and initial level to high (3.3v)
	GPIO.setup(LedPin, GPIO.OUT, initial=GPIO.HIGH)
	# Set BtnPin's mode to input, 
	# and pull up to high (3.3V)
	GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
	# Set up a falling detect on BtnPin, 
	# and callback function to swLed
	GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed)
# Define a callback function for button callback
def swLed(ev=None):
	global Led_status
	# Switch led status(on-->off; off-->on)
	Led_status = not Led_status
	GPIO.output(LedPin, Led_status)
	if Led_status:
		print 'LED OFF...'
	else:
		print '...LED ON'
# Define a main function for main process
def main():
	# Print messages
	print_message()
	while True:
		# Don't do anything.
		time.sleep(1)
# Define a destroy function for clean up everything after
# the script finished 
def destroy():
	# Turn off LED
	GPIO.output(LedPin, GPIO.HIGH)
	# Release resource
	GPIO.cleanup()
# If run this script directly, do:
if __name__ == '__main__':
	setup()
	try:
		main()
	# When 'Ctrl+C' is pressed, the child program 
	# destroy() will be  executed.
	except KeyboardInterrupt:
		destroy()

See a PDF copy of the tutorial here – <Link>

About the Raspberry Pi

The Raspberry Pi is a series of small single-board computers developed in the United Kingdom by the Raspberry Pi Foundation to promote the teaching of basic computer science in schools and in developing countries. It is a capable little computer which can be used in electronics projects, and for many of the things that your desktop PC does, like spreadsheets, word processing, browsing the internet, and playing games. The original model became far more popular than anticipated, selling outside its target market for uses such as robotics.

The Raspberry Pi does not include peripherals (such as keyboards, mice and cases). However, some accessories have been included in several official and unofficial bundles. According to the Raspberry Pi Foundation, over 5 million Raspberry Pis were sold by February 2015, making it the best-selling British computer. By November 2016 they had sold 11 million units, and 12.5m by March 2017, making it the third best-selling “general purpose computer”. In July 2017, sales reached nearly 15 million.In March 2018, sales reached 19 million. Most Pis are made in a Sony factory in Pencoed, Wales; some are made in China or Japan.

You can read more about the Raspberry Pi here – RaspberryPi.org.

Prerequisites

  1. This development track is based on the Rasbperry Pi and the SunFounder Super Starter Kit v3.0 for the Raspberry Pi.
  2. You will need access to both the Raspberry Pi 3 B and the electronics components part of the SunFounder Super Starter Kit v3.0 for the Raspberry Pi  kit to be able to work on these tutorials.
  3. If you haven’t purchased the Raspberry Pi 3 B yet please head over to our store and purchase one now. You can pick up the SunFounder Super Starter Kit v3.0 for the Raspberry Pi from SunFounder’s website.
  4. Depending on where you live you might also be able to pick up the Raspberry Pi and SunFounder Super Starter Kit v3.0 for the Raspberry Pi at your local electronics hobby store.
  5. You can read more about the Raspberry Pi here – RaspberryPi.org.

Questions