• sales

    +86-0755-88291180

RPi Tutorial Series: Getting Started with lighting up an LED User Guide

Raspberry Pi is not only a mini PC but also an IoT kit which can be used to control electrical equipments via the GPIO pins. Many Geeks fell in love with hardware developments and started with blinking an LED. I won't explain how romantic it was but you can start your development journey from lighting up an LED with your Pi.

Control GPIO via Shell Script

To setup a GPIO for future use, please first change the current directory to /sys/class/gpio.

cd /sys/class/gpio

List the files and you will find there are only such files: export, gpiochipN and unexport (here gpiochipN stands for a GPIO controller implementing GPIOs starting at #N, see: Documentation of sysfs. On Raspberry Pi, N is a number often be 0)

ls

Here we are trying to setup GPIO26 for future use by the command:

echo 26 > export

You might have questions about the > symbol. > symbol is a Redirection Operators which is often used to save the output of a command to a file. In fact we add the number 26 to the file export, and the system will generate a new gpio directory gpio26. You can also add another gpio by editing the file export, e.g. with sudo nano export, and append 27 then save it, which also make the system generate a new directory gpio27. Change the current directory to gpio26.

cd gpio26

You will find such files or dircotories: active_low, direction, edge, power, subsystem, uevent, value with ls command. Set GPIO26 as output:

echo out > direction

Set BCM_GPIO26 as high level:

echo 1 > value

Set BCM_GPIO26 as low level:

echo 0 > value

Reverses the effect of exporting:

cd ..
echo 26 > unexport

You can also write the commands as a shell script like:

vi led.sh

Add:

#! /bin/bash
echo Exporting pin $1
echo $1 > /sys/class/gpio/export
echo Setting direction to out.
echo out > /sys/class/gpio/gpio$1/direction
echo Setting pin $2
echo $2 > /sys/class/gpio/gpio$1/value

Then give the executable permission to the script:

chmod +x led.sh

the first line #! /bin/bash asks the system to execute the script with /bin/bash , $1 and $2 stand for the 1st and 2nd parameters that you can change the state of GPIO26 with easier commands:

sudo ./led.sh 26 1
sudo ./led.sh 26 0

Furthermore you can even control the GPIO pins with .c programs. See: RPi GPIO Code Samples When using c program to control GPIOs, remember to compile with:

gcc filename.c -o led 

then

sudo ./led

A makefile is very helpful for easy compilation, for example, save the commands to a empty file named Makefile:

led:led.c
    gcc led.c -o led
clean:
    rm led

and then you can compile the led.c program with:

make

clean the files auto-generated in compilation process:

make clean

Besides, we provide a Pioneer600 demo for GPIO control which might be very helpful. If you feel hard to connect an LED between the GPIO pin and GND, the extension board Pioneer600 might be a good choice to test the code above. Pioneer600 is embeded with peripherals such as serial port, LEDs, OLED screens and AD/DA chips.

Control GPIO based on C Libraries

Now you've learned how to control GPIO by Shell Script, but probably the c program is too verbose to implements so here we introduce a middle tier libraries for GPIO control - WiringPi and BCM2835.

WiringPi

WiringPi is a GPIO access library written in C for the BCM2835 used in the Raspberry Pi. If you have an Arduino board, you will find that the functions of WiringPi just like the Wiring language on Arduino. See: http://wiringpi.com/

WiringPi Installation

Some operating systems (e.g. Raspbian) may have contained WiringPi whose version can be checked by the command gpio -v, but you can also get and install the WiringPi source code manually with these command:

git clone git://git.drogon.net/wiringPi
cd wiringPi
./build

The build script will help you install the library. You can download it from https://git.drogon.net/?p=wiringPi;a=summary (click snapslot), or from this Wiki and then extract and install with:

tar zxvf wiringPi-xxx.tar.gz
cd wiringPi-xxx
./build

Here xxx stands for the version. Please see Download and Install Guide for more details.

GPIO Utility

WiringPi comes with a separate program to help manage the GPIO. This program, called gpio, can also be used in scripts to manipulate the GPIO pins. Quote

You can check if it was installed with:

  • get gpio version:
gpio -v
  • get help:
gpio -h

You can get all the GPIO info.

gpio readall

You get:

 +-----+-----+---------+------+---+---Pi 3---+---+------+---------+-----+-----+
 | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 |     |     |    3.3v |      |   |  1 || 2  |   |      | 5v      |     |     |
 |   2 |   8 |   SDA.1 |   IN | 1 |  3 || 4  |   |      | 5V      |     |     |
 |   3 |   9 |   SCL.1 |   IN | 1 |  5 || 6  |   |      | 0v      |     |     |
 |   4 |   7 | GPIO. 7 |   IN | 1 |  7 || 8  | 0 | IN   | TxD     | 15  | 14  |
 |     |     |      0v |      |   |  9 || 10 | 1 | IN   | RxD     | 16  | 15  |
 |  17 |   0 | GPIO. 0 |   IN | 0 | 11 || 12 | 0 | IN   | GPIO. 1 | 1   | 18  |
 |  27 |   2 | GPIO. 2 |   IN | 0 | 13 || 14 |   |      | 0v      |     |     |
 |  22 |   3 | GPIO. 3 |   IN | 0 | 15 || 16 | 0 | IN   | GPIO. 4 | 4   | 23  |
 |     |     |    3.3v |      |   | 17 || 18 | 0 | IN   | GPIO. 5 | 5   | 24  |
 |  10 |  12 |    MOSI |   IN | 0 | 19 || 20 |   |      | 0v      |     |     |
 |   9 |  13 |    MISO |   IN | 0 | 21 || 22 | 0 | IN   | GPIO. 6 | 6   | 25  |
 |  11 |  14 |    SCLK |   IN | 0 | 23 || 24 | 1 | IN   | CE0     | 10  | 8   |
 |     |     |      0v |      |   | 25 || 26 | 1 | IN   | CE1     | 11  | 7   |
 |   0 |  30 |   SDA.0 |   IN | 1 | 27 || 28 | 1 | IN   | SCL.0   | 31  | 1   |
 |   5 |  21 | GPIO.21 |   IN | 1 | 29 || 30 |   |      | 0v      |     |     |
 |   6 |  22 | GPIO.22 |   IN | 1 | 31 || 32 | 0 | IN   | GPIO.26 | 26  | 12  |
 |  13 |  23 | GPIO.23 |   IN | 0 | 33 || 34 |   |      | 0v      |     |     |
 |  19 |  24 | GPIO.24 |   IN | 0 | 35 || 36 | 0 | IN   | GPIO.27 | 27  | 16  |
 |  26 |  25 | GPIO.25 |   IN | 0 | 37 || 38 | 0 | IN   | GPIO.28 | 28  | 20  |
 |     |     |      0v |      |   | 39 || 40 | 0 | IN   | GPIO.29 | 29  | 21  |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
 +-----+-----+---------+------+---+---Pi 3---+---+------+---------+-----+-----+

The table shows the pins with their modes and current values, containing BCM, wPi and Physical for handy cross-reference.

For example, the physical pin 37 is mapped to the pin 25 in WiringPi and pin 26 in BCM library (described later). If you want to set pin 37 as an output pin, you can use this command:

gpio -g mode 26 out

As same as the commands we've learned before:

cd /sys/class/gpio
echo 26 > export
cd gpio26
echo out > direction
echo 1 > value

More exmaple for gpio commands:

# This uses the wiringPi pin numbers to set pin 26 as an output and then sets the pin to a logic 1.
gpio -g mode 26 out
gpio -g write 26 1
# This sets the pin to a logic 0 and then reads pin 26 (return 0).
gpio -g write 26 0 
gpio -g read 26

WiringPi Functions/API

Probably you were not satisfied with only GPIO usage, okay you can get more. WiringPi provides a set of functions (API) which are designed to mimic those in the Arduino Wiring Pi. As other C program, you need to declare the library at the head before using the WiringPi libary:

#include <wiringPi.h>

Then... okay, how to write a Arduino style program? The following sample will let an LED on the 37 pin blink. In order to get the expected result, you can place an LED between the pin and GND or you can choose our product Pioneer600 whose 37 pin is connected to an LED.

#include <wiringPi.h>
char LED = 25;
int main(void)
{
    if(wiringPiSetup() < 0)return 1;
    pinMode (LED,OUTPUT);
    while(1)
    {  
        digitalWrite(LED, 1) ;
        delay (200);
        digitalWrite(LED, 0) ;
        delay (200);
    }  
}

Save as "led.c" and compile the program.

gcc -Wall led.c –o led -lwiringPi 
sudo ./led
  • -Wall means "warn all" which turns on (almost) all the warnings.
  • To compile your program, the param "-lwiringPi" is used to refer wiringPi.h
  • After process terminated by Ctrl + C, the GPIO state remains as the most recent state. However, the LED was blinking during the process, so it is hard to make sure what the last LED state is.

Hit Ctrl + C to terminate the process. This is not enough but we just give a hint to start your coding with wiringPi. Please visit https://projects.drogon.net/raspberry-pi/wiringpi/functions/ for more detailed API document:

BCM2835

BCM2835 is the MCU chip of the Raspberry Pi, whose library can often be used to access the GPIO on BCM 2835 chip. You can use the librarty to control the rigistors of a BCM2835 chip directly just like using STM32 library to control an STM32 chip. in contrast, the libraries of WiringPi or Python control GPIO by reading and writing device files on the Linux system.

BCM2835 Installation

You can download the library from BCM2835 website or from this Wiki and then extract and install with:

tar zxvf bcm2835-x.xx.tar.gz
cd bcm2835-x.xx
./configure
make
sudo make check
sudo make install

Example

Create a file called led.c and append:

#include <bcm2835.h>
#define PIN 26
int main(int argc, char **argv)
{
    if (!bcm2835_init())return 1;
    bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {  
        bcm2835_gpio_write(PIN, HIGH);
        bcm2835_delay(200);
        bcm2835_gpio_write(PIN, LOW);
        bcm2835_delay(200);
    }  
    bcm2835_close();
    return 0;
}

Compile and execute the program:

gcc -Wall led.c -o led -lbcm2835
sudo ./led
  • -Wall means "warn all" which turns on (almost) all the warnings.
  • To compile your program, the param "-lbcm2835" is used to refer bcm2835.h
  • Like using WiringPi, it is hard to make sure what the last LED state is.

Python

RPI.GPIO Installation

The python library for Raspberry Pi GPIO often comes with the latest Raspbian OS but you can also install it manually from https://pypi.python.org/pypi/RPi.GPIO

Then:

# Install the package python-dev
sudo apt-get install python-dev
# Installing the RPi.GPIO package (GPIO interface functions). Copy the installation package RPi.GPIO to your Pi and extract it. Then install with:
sudo python setup.py install
# Install the library smbus (I2C interface functions)
sudo apt-get install python-smbus
# Install the library serial, which contains UART interface functions
sudo apt-get install python-serial
# Installing the library spidev (SPI functions). Copy the installation package spidev to your Pi and extract it. Then install with:
sudo python setup.py install

Example

Create an led.py file and append:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import time
LED = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED,GPIO.OUT)
try:
    while True:
        GPIO.output(LED,GPIO.HIGH)
        time.sleep(1)
        GPIO.output(LED,GPIO.LOW)
        time.sleep(1)
except:
    print("except")
GPIO.cleanup()

You can run the python program without compile:

sudo python led.py
  • #!/usr/bin/python is a shebang line that defines where the interpreter is located at.
  • GPIO.setmode(GPIO.BCM) sets the pins in BCM numbering mode.
  • After process terminated by Ctrl + C, the program catches an interrupted exception and execute the lines in except block, that clean up GPIO states with logic 0.
  • You can get python tutorials from http://www.runoob.com/python/python-tutorial.html
  • There is also a WiringPi library for python that may interest you: https://github.com/WiringPi/WiringPi2-Python