Interfacing with GPIO pins

As mentioned earlier, GPIO pins are a great way to interface with physical devices such as buttons and LEDs. Python is one of the most popular scripting languages on the Banana Pi (and Linux in general). When working with the Raspberry Pi, you have access to RPi.GPIO, a library to work with the GPIO pins in Python. Since the Banana Pi is slightly different, there is a modified version you will need to grab from the LeMaker GitHub page at https://github.com/LeMaker/RPi.GPIO_BP.

A single command will download the package from GitHub for you onto the Banana Pi:

git clone https://github.com/LeMaker/RPi.GPIO_BP -b bananapi

You can easily install this library by running the following commands:

sudo apt-get update
sudo apt-get install python-dev
cd ./RPi.GPIO_BP
python setup.py install
sudo python setup.py install

You will need to install setup.py both with and without sudo. This will facilitate the installation of the necessary components to the root user as well as your current user. Once this is done, you will be ready to start interfacing with the GPIO pins.

Interacting with the GPIO pins in Python

So, now that you have the Banana Pi flavor of the GPIO library installed, we can start to write some basic code to interface with the pins. We will start by creating the Python script we want to work out of, using the following command:

sudo nano gpio.py

This command will open the nano editor in which we can actually write some Python code:

#!/usr/bin/env python
import RPi.GPIO as GPIO

#Use BCM numbering
GPIO.setmode(GPIO.BCM)

This command will tell the program to use the BCM option, which will use the Broadcom SoC numbering. This numbering is actually different from the versions of Raspberry Pi. However, we don't need to worry about that for the Banana Pi, because there is only one version currently.

We will take what we just wrote and add some script to it in order to create a simple script that will blink an LED on pin 7:

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
PIN_NUM = 7
#Use BCM numbering
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_NUM, GPIO.OUT)
GPIO.output(PIN_NUM, GPIO.LOW)
while True:
        GPIO.output(PIN_NUM, GPIO.HIGH)
        time.sleep(1)
        GPIO.output(PIN_NUM, GPIO.LOW)
        time.sleep(1)

This simple script illustrates how easy it is to write a small amount of code and interact with a physical piece of hardware. We will work more with the GPIO pins in the upcoming sections while we tackle topics such as sensors.

The following screenshot shows the code we just wrote in the nano editor on the Banana Pi:

Interacting with the GPIO pins in Python
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.36.239