Lighting LED using Raspberry Pi
To lighting LED using Raspberry Pi we first need Python GPIO. In my previous post on Raspberry pi we have installed raspbian. Next thing is to start experimenting on it. In this post we will see how you can setup your pi to run Python and create your first Project.
As a first step we need to make sure that we have Python GPIO library installed and working. To do so follow the following steps.
Installing The Python GPIO Library
Python should already be installed in your Raspberry Pi. Next step would be to install GPIO library.
Installation
If you have the latest version of Raspbian then most likely Rpi.GPIO is pre-installed. You just need to update your library using the following commands.
sudo python
import RPi.GPIO as GPIO
GPIO.VERSION
To update the library use following commands.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install rpi.gpio
Alternate way to install Python GPIO Library:
- Type the following command to download the GPIO library as a tarball:
wget http://raspberry-gpio-python.googlecode.com/files/RPi.GPIO-0.4.1a.tar.gz - Unzip the tarball:
tar zxvf RPi.GPIO-0.4.1a.tar.gz - Change to the directory where tarball was inflated:
cd RPi.GPIO-0.4.1a - Install the GPIO library in Python:
sudo python setup.py install
Important: You must be a superuser to run scripts that control the GPIO pins on your RPi. If you are using the IDLE IDE to write your Python scripts, be sure to launch it as a superuser.
Your first Project – lighting up a LED
Parts Required:
- Raspberry Pi 2 ( you can use Pi 3)
- A small LED( any colour, I have used RED)
- 1 100 ohm resistance
- Some wires/connectors
- Breadboard
At first we will start with lighting the LED with 3.3v pin of Raspberry Pi. For this use the following Schematic:
- Pin 1 (+3.3 volts) should go to the longer leg of your led. This pin provides a steady supply of 3.3v. Unlike the GPIO pins on your Pi, this pin is not programmable, and cannot be controlled by software.
- Attach the shorter leg of the led to the resistor. Finally, attach the other end of the resistor to Pin 6 (- GND) on your Pi
If everything goes well, LED should light up when turning on the Raspberry Pi.
Next, we will make this LED to blink by using the GPIO pin 4( or board Pin 7). For this we will write small piece of code in Python.
Launch idle IDE as superuser(root).
sudo idle
type following into the code window and save the file as python1.py
import RPi.GPIO as GPIO import time GPIO.setwarnings(True) GPIO.setmode(GPIO.BCM) ## Use BCM pin numbering GPIO.setup(4, GPIO.OUT) ## Setup GPIO Pin 7 to OUT while True : GPIO.output(4,True) time.sleep(5) GPIO.output(4,False) time.sleep(5)
Make connections as shown below:
To run the code press ctrl+f5. You show now see LED blinking with a delay of 5 sec. That’s it for now. We will see some complex code in next post.