Raspberry Pi Beginners Tutorial 1: Switching a single LED on
A simple tutorial introducing you to controlling the Raspberry Pi's GPIO pins.
As well as being a miniature all-in-one computer, your Raspberry Pi also gives you access to its processor’s General Purpose Input/Output (GPIO) pins. These pins allow you to control electrical circuits by running commands on the Raspberry Pi.
Set up the following circuit using a coloured LEDs and a 330 ohm resistor.
If you look closely at the LED you will see two small pieces of metal inside. These are called the Anode and the Cathode. The Cathode is the larger piece of the two and this leads to the negative pin of the LED.
Once this has been set up, load up IDLE on the Raspberry Pi (Menu > Programming > Python 2 (IDLE)). You can now switch the LED on and off by using the following lines of code:
First we need to load the drivers for the GPIO pins:
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM)
Then we need to declare that we are using GPIO pin 17 as an Output control.
We now just need to send a signal through the GPIO pin. Once you have executed the following code the LED should light up.
To switch the LED back of, you just need to run the following code.
Using a Python Script
It wouldn’t be very practical to have to type each of the above lines each time you want to switch the light on. So now that you have tested your circuit you can now combine all of these lines into a single script.
Open IDLE on your Raspberry Pi and open a new project (File > New File). Then type the following:
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17, True)
Save your project as lightswitch.py (File > Save As) in your Documents folder.
Open Terminal (Menu > Accessories > Terminal) and navigate to your Documents folder by typing the following:
Now type the following to run your new script:
The LED will light up.
Now go back to IDLE and change the last line of the script to the following and save your script (File > Save):
Now type the following command again in Bash:
The LED will switch back off.