Reader small image

You're reading from  Raspberry Pi LED Blueprints

Product typeBook
Published inSep 2015
Publisher
ISBN-139781782175759
Edition1st Edition
Right arrow
Author (1)
Agus Kurniawan
Agus Kurniawan
author image
Agus Kurniawan

Agus Kurniawan is an independent technology consultant, author, and lecturer. He has over 18 years' experience working on various software development projects, including delivering training courses and workshops, and delivering technical writing. He has done a few research activities related to wireless networking, software, and security in multiple universities. Currently, he is pursuing a Ph.D. program in Computer Science in Germany. He has previously written five books for Packt.
Read more about Agus Kurniawan

Right arrow

Chapter 1. Getting Started with LED Programming through Raspberry Pi GPIO

In this chapter, you will learn the basics of Raspberry Pi GPIO and LED development so that you can be sure that you have the basic required knowledge to develop LED programming through Raspberry Pi GPIO.

The following topics will be the major takeaways from this chapter:

  • Setting up Raspberry Pi

  • Introducing Raspberry Pi GPIO

  • Blinking LEDs

  • Turning an LED on/off using a push button

  • Changing color through an RGB LED

Setting up Raspberry Pi


Raspberry Pi is a low-cost, credit card-sized computer that you can use to develop a general-purpose computer. There are several Raspberry Pi models that you can use to develop what you want. For illustration, this book will use a Raspberry Pi 2 board. Check https://www.raspberrypi.org/products/, which offers the Raspberry Pi 2 Model B board.

You can also see a video of the unboxing of Raspberry Pi 2 Model B from element14 on YouTube at https://www.youtube.com/watch?v=1iavT62K5q8.

To make Raspberry Pi work, we need an OS that acts as a bridge between the hardware and the user. There are many OS options that you can use for Raspberry Pi. This book uses Raspbian as an OS platform for Raspberry Pi. Raspbian OS is an operating system based on Debian with a targeting ARM processor. You can use another OS platform for Raspberry Pi from https://www.raspberrypi.org/downloads/. To deploy Raspbian with Raspberry Pi 2 Model B, we need a microSD card of at least 4 GB in size, but the recommended size is 8 GB. For testing purposes, we will use Raspbian as an operating system platform for Raspberry Pi.

You can set up your Raspberry Pi with the Raspbian image by following the instructions on this website, QUICK START GUIDE, https://www.raspberrypi.org/help/quick-start-guide/.

After having installed and deployed Raspbian, you can run the Raspbian desktop GUI by typing the following command on the terminal:

startx

This command makes Raspbian load the GUI module from the OS libraries. You can then see the Raspbian desktop GUI as follows:

Introducing Raspberry Pi GPIO


General-purpose input/output (GPIO) is a generic pin on Raspberry Pi, which can be used to interact with external devices, such as sensor and actuator devices. You can see the Raspberry Pi GPIO pinouts in the following figure (source: http://www.element14.com/community/docs/DOC-73950/l/raspberry-pi-2-model-b-gpio-40-pin-block-pinout):

To access Raspberry Pi GPIO, we can use several GPIO libraries. If you are working with Python, Raspbian will have already installed the RPi.GPIO library to access Raspberry Pi GPIO. You can read more about RPi.GPIO at https://pypi.python.org/pypi/RPi.GPIO. You can verify the RPi.GPIO library from a Python terminal by importing the RPi.GPIO module, as shown in the following screenshot:

If you don't find this library on Python runtime or get the error message ImportError: No module named RPi.GPIO, you can install it by compiling from the source code. For instance, we want to install RPi.GPIO 0.5.11, so type the following commands:

wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar.gz
tar -xvzf RPi.GPIO-0.5.11.tar.gz
cd RPi.GPIO-0.5.11/
sudo python setup.py install

Tip

To install and update through the apt command, your Raspberry Pi must be connected to the Internet.

Another way to access Raspberry Pi GPIO is to use WiringPi. It is a library written in C for Raspberry Pi to access GPIO pins. You can read information about WiringPi from the official website http://wiringpi.com/.

To install WiringPi, you can type the following commands:

sudo apt-get update
sudo apt-get install git-core
git clone git://git.drogon.net/wiringPi
cd wiringPi
sudo ./build

Please make sure that your Pi network does not block the git protocol for git://git.dragon.net/wiringPi. This code can be browsed on https://git.drogon.net/?p=wiringPi;a=summary.

The next step is to install the WiringPi interface for Python, so you can access Raspberry Pi GPIO from a Python program. Type the following commands:

sudo apt-get install python-dev python-setuptools
git clone https://github.com/Gadgetoid/WiringPi2-Python.git
cd WiringPi2-Python
sudo python setup.py install

When finished, you can verify it by showing a GPIO map from the Raspberry Pi board using the GPIO tool:

gpio readall

If this is successful, you should see the GPIO map from the Raspberry Pi board on the terminal:

You can also see values in the wPi column, which will be used in the WiringPi program as GPIO value parameters. I will show you how to use it in the WiringPi library in the next section.

Blinking LEDs


In this section, we will build a simple app that interacts with Raspberry Pi GPIO. We will use three LEDs, which are attached to the Raspberry Pi 2 board. Furthermore, we will turn the LEDs on/off sequentially.

The following hardware components are needed:

  • Raspberry Pi 2.(you can change this model)

  • Three LEDs of any color

  • Three resistors (330 Ω or 220 Ω)

The hardware wiring can be implemented as follows:

  • LED 1 is connected to Pi GPIO18

  • LED 2 is connected to Pi GPIO23

  • LED 3 is connected to Pi GPIO24

The following image shows the hardware connection for LED blinking:

Now you can write a program using WiringPi with Python. The following is the complete Python code for blinking LEDs:

# ch01_01.py file

import wiringpi2 as wiringpi
import time

# initialize
wiringpi.wiringPiSetup()

# define GPIO mode
GPIO18 = 1
GPIO23 = 4
GPIO24 = 5
LOW = 0
HIGH = 1
OUTPUT = 1
wiringpi.pinMode(GPIO18, OUTPUT)
wiringpi.pinMode(GPIO23, OUTPUT)
wiringpi.pinMode(GPIO24, OUTPUT)


# make all LEDs off
def clear_all():
    wiringpi.digitalWrite(GPIO18, LOW)
    wiringpi.digitalWrite(GPIO23, LOW)
    wiringpi.digitalWrite(GPIO24, LOW)

# turn on LED sequentially
try:
    while 1:
        clear_all()
        print("turn on LED 1")
        wiringpi.digitalWrite(GPIO18, HIGH)
        time.sleep(2)
        clear_all()
        print("turn on LED 2")
        wiringpi.digitalWrite(GPIO23, HIGH)
        time.sleep(2)
        clear_all()
        print("turn on LED 3")
        wiringpi.digitalWrite(GPIO24, HIGH)
        time.sleep(2)

except KeyboardInterrupt:
    clear_all()

print("done")

Save this script in a file named Python ch01_01.py.

Moreover, you can run this file on the terminal. Type the following command:

sudo python ch01_01.py

You should see three LEDs blinking sequentially. To stop the program, you can press CTRL+C on the Pi terminal. The following is a sample of the program output:

Based on our wiring, we connect three LEDs to GPIO18, GPIO23, and GPIO24 from the Raspberry Pi board. You can see these WiringPi GPIO values from the gpio readall command and find GPIO18, GPIO23, and GPIO24 recognized as (the wPi column) 1, 4, and 5, respectively.

First, we initialize WiringPi using wiringpi.wiringPiSetup(). Then, we define our GPIO values and set their modes on Raspberry Pi as follows:

GPIO18 = 1
GPIO23 = 4
GPIO24 = 5
LOW = 0
HIGH = 1
OUTPUT = 1
wiringpi.pinMode(GPIO18, OUTPUT)
wiringpi.pinMode(GPIO23, OUTPUT)
wiringpi.pinMode(GPIO24, OUTPUT)

Each LED will be turned on using wiringpi.digitalWrite(). time.sleep(n) is used to hold the program for n seconds. Let's set a delay time of two seconds as follows:

clear_all()
print("turn on LED 1")
wiringpi.digitalWrite(GPIO18, HIGH)
time.sleep(2)

The clear_all() function is designed to turn off all LEDs:

def clear_all():
    wiringpi.digitalWrite(GPIO18, LOW)
    wiringpi.digitalWrite(GPIO23, LOW)
    wiringpi.digitalWrite(GPIO24, LOW)

Turning an LED on/off using a push button


In the previous section, we accessed Raspberry Pi GPIO to turn LEDs on/off by program. Now we will learn how to turn an LED on/off using a push button, which is used as a GPIO input from Raspberry Pi GPIO.

The following hardware components are needed:

You can see the push button connection in the following figure:

Our hardware wiring is simple. You simply connect the LED to GPIO23 from Raspberry Pi. The push button is connected to Raspberry Pi GPIO on GPIO24. The complete hardware wiring can be seen in the following figure:

Furthermore, you can write a Python program to read the push button's state. If you press the push button, the program will turn on the LED. Otherwise, it will turn off the LED. This is our program scenario.

The following is the complete code for the Python program:

# ch01_02.py file

import wiringpi2 as wiringpi

# initialize
wiringpi.wiringPiSetup()

# define GPIO mode
GPIO23 = 4
GPIO24 = 5
LOW = 0
HIGH = 1
OUTPUT = 1
INPUT = 0
PULL_DOWN = 1
wiringpi.pinMode(GPIO23, OUTPUT)  # LED
wiringpi.pinMode(GPIO24, INPUT)  # push button
wiringpi.pullUpDnControl(GPIO24, PULL_DOWN)  # pull down


# make all LEDs off
def clear_all():
    wiringpi.digitalWrite(GPIO23, LOW)

try:
    clear_all()
    while 1:
        button_state = wiringpi.digitalRead(GPIO24)
        print button_state
        if button_state == 1:
            wiringpi.digitalWrite(GPIO23, HIGH)
        else:
            wiringpi.digitalWrite(GPIO23, LOW)

        wiringpi.delay(20)

except KeyboardInterrupt:
    clear_all()

print("done")

Save this code in a file named ch01_02.py.

Now you can run this program via the terminal:

$ sudo python ch01_02.py

After this, you can check by pressing the push button; you should see the LED lighting up.

First, we define our Raspberry Pi GPIO's usage. We also declare our GPIO input to be set as pull down. This means that if the push button is pressed, it will return value 1.

GPIO23 = 4
GPIO24 = 5
LOW = 0
HIGH = 1
OUTPUT = 1
INPUT = 0
PULL_DOWN = 1
wiringpi.pinMode(GPIO23, OUTPUT)  # LED
wiringpi.pinMode(GPIO24, INPUT)  # push button
wiringpi.pullUpDnControl(GPIO24, PULL_DOWN)  # pull down

We can read the push button's state using the digitalRead() function from WiringPi as follows:

button_state = wiringpi.digitalRead(GPIO24)

If the push button is pressed, we turn on the LED; otherwise, we turn it off:

print button_state
if button_state == 1:
    wiringpi.digitalWrite(GPIO23, HIGH)
else:
    wiringpi.digitalWrite(GPIO23, LOW)

Changing color through an RGB LED


The last demo of basic LED programming is to work with an RGB LED. This LED can emit monochromatic light, which could be one of the three primary colors—red, green, and blue, known as RGB.

The RGB LED connection is shown in the following figure:

In this section, we will build a simple program to display red, green, and blue colors through the RGB LED.

The following hardware components are needed:

Our hardware wiring can be implemented as follows:

  • RGB LED pin 1 is connected to Raspberry Pi GPIO18

  • RGB LED pin 2 is connected to Raspberry Pi VCC +3 V

  • RGB LED pin 3 is connected to Raspberry Pi GPIO23

  • RGB LED pin 4 is connected to Raspberry Pi GPIO24

The complete hardware wiring can be seen in the following figure:

Returning to the Raspberry Pi terminal, you could write a Python program to display color through RGB LED. Let's create a file named ch01_03.py and write this script as follows:

# ch01_03.py file

import wiringpi2 as wiringpi
import time

# initialize
wiringpi.wiringPiSetup()

# define GPIO mode
GPIO18 = 1  # red
GPIO23 = 4  # green
GPIO24 = 5  # blue
LOW = 0
HIGH = 1
OUTPUT = 1
wiringpi.pinMode(GPIO18, OUTPUT)
wiringpi.pinMode(GPIO23, OUTPUT)
wiringpi.pinMode(GPIO24, OUTPUT)


# make all LEDs off
def clear_all():
    wiringpi.digitalWrite(GPIO18, HIGH)
    wiringpi.digitalWrite(GPIO23, HIGH)
    wiringpi.digitalWrite(GPIO24, HIGH)


def display(red, green, blue):
    wiringpi.digitalWrite(GPIO18, red)
    wiringpi.digitalWrite(GPIO23, green)
    wiringpi.digitalWrite(GPIO24, blue)


try:
    while 1:
        clear_all()
        print("red")
        display(0, 1, 1)
        time.sleep(2)
        clear_all()
        print("green")
        display(1, 0, 1)
        time.sleep(2)
        clear_all()
        print("blue")
        display(1, 1, 0)
        time.sleep(2)
        clear_all()
        print("white")
        display(0, 0, 0)
        time.sleep(2)
        clear_all()
        print("110")
        display(1, 1, 0)
        time.sleep(2)
        clear_all()
        print("101")
        display(1, 0, 1)
        time.sleep(2)
        clear_all()
        print("011")
        display(0, 1, 1)
        time.sleep(2)

except KeyboardInterrupt:
    clear_all()

print("done")

Save this script. You can run this file by typing the following command:

$ sudo python ch01_03.py

Then, you should see that the RGB LED displays a certain color every second. The program output can also write a message indicating which color is currently on the RGB LED:

The RGB LED can display a color by combining three basic colors: red, green, and blue. First, we initialize Raspberry Pi GPIO and define our GPIO usage:

# initialize
wiringpi.wiringPiSetup()

# define GPIO mode
GPIO18 = 1  # red
GPIO23 = 4  # green
GPIO24 = 5  # blue
LOW = 0
HIGH = 1
OUTPUT = 1
wiringpi.pinMode(GPIO18, OUTPUT)
wiringpi.pinMode(GPIO23, OUTPUT)
wiringpi.pinMode(GPIO24, OUTPUT)

For instance, to set a red color, we should set LOW on the red pin and HIGH on both green and blue pins. We define the display() function to display a certain color on the RGB LED with the red, green, and blue values as parameters as follows:

def display(red, green, blue):
    wiringpi.digitalWrite(GPIO18, red)
    wiringpi.digitalWrite(GPIO23, green)
    wiringpi.digitalWrite(GPIO24, blue)

In the main program, we display a color via the display() function by passing red, green, and blue values, as shown in the following code:

clear_all()
print("red")
display(0, 1, 1)
time.sleep(2)
clear_all()
print("green")
display(1, 0, 1)
time.sleep(2)
clear_all()
print("blue")
display(1, 1, 0)
time.sleep(2)
clear_all()
print("white")
display(0, 0, 0)
time.sleep(2)
clear_all()
print("110")
display(1, 1, 0)
time.sleep(2)
clear_all()
print("101")
display(1, 0, 1)
time.sleep(2)
clear_all()
print("011")
display(0, 1, 1)
time.sleep(2)

Summary


Let's summarize what we have learned in this chapter. We connected three LEDs to a Raspberry Pi board. After that, we made these LEDs blink. Then, we read the Raspberry Pi GPIO input. Finally, we learned to display several colors through an RGB LED.

In the next chapter, we will work with 7-segment display and a shift register to manipulate several 7-segment display modules. We will also build a countdown timer app by utilizing a 7-segment module.

You have been reading a chapter from
Raspberry Pi LED Blueprints
Published in: Sep 2015Publisher: ISBN-13: 9781782175759
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Agus Kurniawan

Agus Kurniawan is an independent technology consultant, author, and lecturer. He has over 18 years' experience working on various software development projects, including delivering training courses and workshops, and delivering technical writing. He has done a few research activities related to wireless networking, software, and security in multiple universities. Currently, he is pursuing a Ph.D. program in Computer Science in Germany. He has previously written five books for Packt.
Read more about Agus Kurniawan