After successfully installing raspbian into Raspberry PI, the first thing which comes into the mind of the embedded developer is to play with Raspberry PI GPIO. Because the very best advantage of this cheap computer is to use with external hardware through its GPIO. We are going to explain how to play with Rasberry PI GPIO’s using PYTHON language.
Here is Quick Look of hardware setup
and the putty screen from start to finish including types of errors that you may or may not face.
Installing Library for Raspberry PI GPIO
Before start using and playing with GPIOs of Raspberry Pi, we need to install its dependent library in raspbian OS. We can add this library through this simple sudo command.
sudo apt-get install rpi.gpio
But before installing this library make it sure that your OS is updated and fully upgraded. But if this is not the case you can simply do this by providing these two simple commands
sudo apt-get update sudo apt-get upgrade
BOARD vs BCM
We can access Raspberry PI GPIO pins in two modes. 1st is Board and 2nd is BCM. Board is simply the pin number order in which that pin appears in Raspberry PI’s GPIO header. On the other hand, the BCM mode is pin numbering according to Broadcom chip.
LED ON OFF Code
In this tutorial, we are using BOARD pins of 16 and 18. You may use any other if you wish. Before start blinking the LED let’s learn how to turn it ON and OFF. We had attached our LED in common Cathod mode mean we had provided zero voltages to its cathode via 330ohm Resistance to limit the current flow. Which makes it pretty clear that to Light up LED we need to provide Logic HIGH to the anode terminal of the LED. So we do this by using the following snippet of code in python.
import RPi.GPIO as GPIO #import GPIO library and name it GPIO #setting board mode GPIO.setmode(GPIO.BOARD) #tell GPIO API to use pin 16 as an OUTPUT mode GPIO.setup(16,GPIO.OUT) #trun ON LED by logic HIGH GPIO.output(18,GPIO.HIGH) #this will give a logic high to ON the LED #turn LED OFF with Logic LOW GPIO.output(18,GPIO.LOW) #with LOW logic result LED to turn OFF
Above simple code will let you turn on and off the led
Blinking LED using Raspberry PI GPIO API
Now we can easily turn above code into a blinky program. We simply need to use some timing function which can put some delay in between this on and off logic. We can easily accomplish this task via “time” library. Which we can import via following command
import time
and we can give some delay using sleep function like following line of code
time.sleep(0.5) #will result in 500ms delay
So just put everything together and see your LED blinking. Here is full blinky program link