• EUR€
  • £GBP
  • $USD
NEWS Raspberry Pi

Python Libraries Uncovered PinPong: How to control the GPIO and I2C of Raspberry Pi

DFRobot Sep 22 2023 3084

In this article, we delve into the strategic application of "Python Libraries" - RPi.GPIO and PinPong, effectively manipulating the "Raspberry Pi GPIO" and "Raspberry Pi I2C" of the "Raspberry Pi". Providing step-by-step instructions and detailed Python codes, this guide empowers readers to utilize these two libraries for various programming tasks on the Raspberry Pi. Whether you're new to Python or an experienced developer, the insights and practices shared here will illuminate the effective use of "Python Libraries" for managing "Raspberry Pi GPIO" and "Raspberry Pi I2C". With these tools at your disposal, you will be well-equipped to fully harness the power of Python in your exploration of the vast microcomputer world that Raspberry Pi offers.

Python is an exceptionally potent language, and should you harbor the desire to embark upon the journey of learning Python, an abundance of invaluable resources can be found strewn across the vast expanse of the internet. Among them, one can effortlessly procure a wealth of videos, tutorials, documents, and developer guides.

Upon perusal of the most current chronicle of programming language rankings, one would discern Python resplendently reigning supreme at the forefront.

chronicle of programming language rankings

Origin: https://hellogithub.com/report/tiobe/


Why has the Python language garnered such widespread adoration? Enriching oneself with Python yields the capacity for manifold accomplishments:

  • 1.Python proves exceedingly advantageous for crafting server-side code, for it bestows a manifold array of libraries replete with preexisting intricate backend functions.
  • 2.Python scripts find ubiquitous employment among programmers, who harness them to automize a myriad of daily tasks, such as the batch conversion of files into alternative formats.
  • 3.Within the realm of AI and machine learning, Python serves as the tool of choice for data scientists embarking on a plethora of data-driven endeavors, including the rectification and eradication of flawed information, commonly referred to as data cleansing.
  • 4.Software developers frequently employ Python for a diverse range of development assignments and software applications, availing themselves of graphical user interface (GUI) libraries to usher forth desktop applications.

However, one may ascertain that Python predominantly finds its purpose in software development, data manipulation, and the like. Consequently, when endeavoring to amalgamate the realms of physicality and innovation in the pursuit of maker-esque projects, one might discern a dearth of information and Python libraries tailored to suit such endeavors. Therefore, in the ensuing discourse, as a maker at heart, our focus shall center upon expeditiously fabricating maker projects utilizing the bedrock of the Python language.


1. Implementing Blink with basic GPIO control of Raspberry Pi using Python

Firstly, we opt for Raspberry Pi as the hardware capable of running Python, utilizing various Python hardware control libraries to achieve the desired Blink effect.

Preparation of required software and hardware for the project:

Hardware device: Raspberry Pi

System environment: Linux system installed and Python IDLE functioning smoothly

Hardware connection diagram:

Connect the positive terminal of the LED to pin 7 (GPIO4), and connect the negative terminal to a resistor linked to the ground pin.

Hardware diagram of the Blink project

Figure: Hardware diagram of the Blink project

Blink project on the Raspberry Pi using the RPi.GPIO library

When it comes to controlling GPIO on the Raspberry Pi to achieve the Blink project, for makers who have dabbled with Raspberry Pi, nothing is more familiar than the RPi.GPIO library. This remarkable library enables you to craft Python programs that exert command over the GPIO pins of the Raspberry Pi. Among the various libraries available, such as pigpio and gpiozero, RPi.GPIO stands out as the most prevalent and refined one in use. Leveraging the kernel of the Linux operating system, we can manipulate GPIO by directly interfacing with files through Python.


Raspberry Pi Pin Definition Chart

Figure: Raspberry Pi Pin Definition Chart

Raspberry Pi RPi.GPIO Code

#import the GPIO and time package
import RPi.GPIO as GPIO
import time
GPIO.setup(4, GPIO.OUT)
# loop through 50 times, on/off for 1 second
for i in range(50):
  • BCM Numbering System: The BCM numbering system is based on the Broadcom chip's pin numbering on the Raspberry Pi. These numbers are fixed and unaffected by specific Raspberry Pi models. When using the BCM numbering system, you need to reference the pin's BCM number for programming purposes.
  • BOARD Numbering System: The BOARD numbering system is based on the physical location of the pins on the Raspberry Pi's board. Each specific Raspberry Pi model has a different physical pin layout. Therefore, when using the BOARD numbering system, you need to reference the pin's physical position for programming purposes.

Blink project on the Raspberry Pi using the PinPong library

PinPong is a Python library developed by DFRobot for controlling open-source hardware mainboards. With PinPong, you can programmatically control various common open-source hardware using a unified Python code. Let's now use the PinPong library to implement Blink on the Raspberry Pi.

PinPong Library Link: https://pinpong.readthedocs.io/

Here's the PinPong code for implementing the Blink project on the Raspberry Pi:

import time
from pinpong.board import Board,Pin

led = Pin(Pin.D4, Pin.OUT) 
while True:

Comparison of Python library implementations for the Blink project:

When it comes to basic GPIO control on the Raspberry Pi, both Python libraries are quite straightforward. While there may be some differences in code syntax, the fundamental usage and logic are similar.

basic GPIO control on the Raspberry Pi

Upon comparing the official descriptions and conducting actual tests, I have discovered that both libraries can achieve several basic functionalities, including:

  • Controlling the input and output of GPIO pins
  • Manipulating the logic level of pins
  • Detecting changes in pin logic level
  • Configuring pull-up and pull-down resistors for pins
  • Generating PWM signals

Now, when it comes to creative projects, additional sensors are often required, such as I2C interface sensors. To further validate the capabilities of RPi.GPIO and PinPong in handling external ultrasonic sensors connected to the Raspberry Pi, let's proceed with an intriguing project involving ultrasonic distance measurement.


2. Python Hardware Control: Creating an Ultrasonic Distance Meter with Raspberry Pi

The ultrasonic distance measurement project involves connecting an ultrasonic sensor to the Raspberry Pi's I2C pins and rapidly retrieving color information while displaying the RGB values through serial communication. The selection of this project aims to better assess the differences between the RPi.GPIO and PinPong libraries when working with certain specialized sensors.

To embark on this project, ensure the following software and hardware preparations:


  • Raspberry Pi
  • Ultrasonic sensor

System environment:

  • Linux system appropriately installed and running Python IDLE

Hardware Connection Diagram:

Connect the I2C interface ultrasonic sensor to the Raspberry Pi's I2C interface.

Raspberry Pi Hardware Connection Diagram

Figure: Raspberry Pi Hardware Connection Diagram


Raspberry Pi Ultrasonic Distance Meter Project using the smbus Library

The Raspberry Pi ultrasonic distance meter project utilizes the smbus library for I2C communication. While the RPi.GPIO documentation mentions the ability to read I2C, there are no specific usage tutorials available. During the search process, an alternative commonly used library for I2C communication on Raspberry Pi, called smbus2, was discovered. This library supplements the limitations of RPi.GPIO in terms of I2C reading capabilities.

Here are the steps to proceed with the project:

  • Step 1: Verify the availability of the Library for Raspberry Pi

Refer to the product's Wiki documentation to confirm the existence of a library specifically designed for the ultrasonic sensor used.

  • Step 2: Import the Ultrasonic Library into Raspberry Pi

Install and import the appropriate library for the ultrasonic sensor mentioned in the Wiki documentation.

  • Step 3: Code Implementation for I2C Ultrasonic Reading and Distance Measurement

Write the necessary code to read the ultrasonic sensor data via the I2C interface and calculate the distance measurements using the imported library.

# -*- coding:utf-8 -*-
import sys
import time
from DFRobot_URM09_RPI import *

urm09 = DFRobot_URM09_IIC(0x01, 0x11)
urm09.set_mode_range(urm09._MEASURE_MODE_AUTOMATIC, urm09._MEASURE_RANG_500)

 while True:
  dist = urm09.get_distance()
  #Read temperature register
  # temp = urm09.get_temperature()
  print("Distance is %d cm         " %dist)
  # print("Temperature is %.2f .c    " %temp)


Ultrasonic Distance Meter Project Demo

Figure: Ultrasonic Distance Meter Project Demo


The Raspberry Pi ultrasonic rangefinder project is built upon the PinPong code

Upon importing PinPong, one can observe through a list that PinPong is compatible with the I2C ultrasonic library, enabling a prompt and direct retrieval of ultrasonic values for speed measurement.

To proceed, please enter the following instructions via the terminal:

Ultrasonic Distance Meter Project Demo

Figure: Ultrasonic Distance Meter Project Demo

import pinpong

module Pinpong libraries supported

Figure: module Pinpong libraries supported

Here is a complete sample code for the ultrasonic rangefinder:

# -*- coding: utf-8 -*-

#RPi and PythonBoard
import time
from pinpong.board import Board
from pinpong.libs.dfrobot_urm09 import URM09 #从libs中导入URM09库


urm = URM09(i2c_addr=0x11, bus_num=1) #初始化传感器,设置I2C地址
urm.set_mode_range(urm._MEASURE_MODE_AUTOMATIC ,urm._MEASURE_RANG_500) #设置URM09模式为自动检测,最大测量距离500cm

while True:
  dist = urm.distance_cm() #读取距离数据,单位厘米(cm)

  print("Distance is %d cm         "%dist)


Ultrasonic Distance Meter Project Demo

Figure: Ultrasonic Distance Meter Project Demo


Comparison of code applications for implementing ultrasonic rangefinders using Python libraries

Through this ultrasonic rangefinder project, it can be observed that RPi.GPIO and smbus libraries have certain limitations:

  • RPi.GPIO provides basic functionality for reading and controlling digital/analog sensors. However, if additional sensors are used, such as ultrasonic or color sensors, you would need to develop separate libraries for these modules.
  • The smbus library allows for reading I2C data but requires a good understanding of coding to achieve the desired results.
  • Alternatively, you can reach out to the respective sensor manufacturers. If the modules are compatible with Raspberry Pi, the manufacturers may provide specific libraries.
  • PinPong offers pre-written libraries for some sensors, allowing for direct implementation and optimized code. This makes it more suitable for novice Python users.


3. A Comparison of RPi.GPIO, Smbus, and PinPong Libraries for Raspberry Pi

Upon researching official documentation and various maker projects available online, it becomes evident that RPi.GPIO is a user-friendly library for Raspberry Pi, particularly suitable for beginners and novices exploring the world of Raspberry Pi. It is an officially recommended library. However, upon careful consideration, it is suggested that novice users should also explore PinPong.

Shared characteristics:

  • Both libraries can fulfill basic Raspberry Pi GPIO control requirements, such as creating projects like Blink and controlling LEDs with buttons.

Points of differentiation:

  • PinPong library provides compatibility with different board controllers.

RPi.GPIO library can only be used with Raspberry Pi, whereas PinPong enables Python-based control of Arduino, micro:bit, and other microcontrollers.

PinPong operates by flashing a specific firmware onto open-source hardware, allowing it to communicate with a computer via serial communication and execute various commands. This means that you can now control your Arduino using Python.

Currently, the PinPong library supports the following board models:

PinPong library supports the following board models:

  • The PinPong library can be installed and run on the major SBC systems, including Mac OS, Linux, and Windows.

With PinPong, you can control GPIO without the need to change your system environment, regardless of the operating system running on your single board computer (SBC) or computer. This means that you can communicate with the computer via a serial port and execute multiple commands.

If you have a high-performance SBC with a Windows operating system and have implemented AI algorithms and data processing using Python, you can effortlessly realize an AI robotics project by directly controlling peripherals such as motors and servos using the Python language.

  • The PinPong library facilitates swift hardware migration for Python projects.

By freeing developers from the constraints imposed by diverse hardware models, it allows them to focus on software implementation. Whether the initial program development is carried out on Arduino and later switched to Raspberry Pi for deployment, a simple modification of hardware parameters enables seamless execution, embodying the principle of "write once, run anywhere."

Switching the controller is as straightforward as generating the corresponding object based on the specified board type and port number when utilizing this library.


Example: Initialization as Arduino UNO

Board("uno").begin()               #Select the board type (Uno, Micro:bit, RPi, Handpy) and port number. If the port number is not provided, automatic recognition will be performed.

Example: Initialization as Raspberry Pi

#Raspberry Pi
Board("rpi").begin()                #Select the board type (Uno, Micro:bit, RPi, Handpy) and port number. If the port number is not provided, automatic recognition will be performed.
  • PinPong offers a wide range of Python libraries for over a hundred commonly used sensors.

Through our previous testing, we have discovered that the quick utilization of many specialized modules relies on dedicated libraries. The developers of PinPong have compiled and continuously developed hardware support libraries for commonly used components such as servos, temperature and humidity sensors like DHT11, and NFC modules, among others, making them readily accessible for direct invocation.

An example project showcasing temperature monitoring for a smart home project:

In this project, an LCD display screen and a temperature sensor are utilized to conveniently view real-time temperature data and display it on the screen. This enables the implementation of a simple smart home temperature monitoring system.

import time
from pinpong.board import Board,Pin
from pinpong.libs.lcd1602 import LCD1602_I2C

Board("uno").begin()#  #Select the board type (Uno, Micro:bit, RPi, Handpy) and port number. If the port number is not provided, automatic recognition will be performed.
adc0 = Pin(Pin.A0, Pin.ANALOG) #Initializing the temperature reading pin to A0.
lcd = LCD1602_I2C(i2c_addr=0x20)#Initializing the I2C address for the LCD display.
lcd.backlight(True) #Turn on the backlight
lcd.clear()#Clear the screen
lcd.set_cursor(2,0)#Set the cursor position
lcd.print('temperature')# Display "temperature"

while True:
    v = adc0.read_analog()#Read the analog value
    tem = round(v*(5/10.24),2)# Convert the read value to temperature data

The current list of module libraries supported by PinPong includes:

  • 1.Servo motor.
  • 2.Buzzer module
  • 3.Ultrasonic sensor (SR04)
  • 4.Temperature and humidity sensor (DHT11)
  • 5.WS2812 RGB LED strip
  • 6.1602 LCD display
  • 7.OLED display
  • 8.Color recognition sensor
  • 9.Infrared thermometer sensro
  • 10.NFC (Near Field Communication) module
  • 11.Air quality sensor
  • 12.I2C BME280 environmental sensor
  • 13.Audio analysis module

To stay updated on the latest module library additions for PinPong, I recommend visiting the official documentation at https://pinpong.readthedocs.io/. After importing PinPong, you will be able to access the up-to-date list of module libraries supported by the current version.

module Pinpong libraries supported

Figure: module Pinpong libraries supported

Through comparative testing, a new Python library called PinPong has been discovered. Why do I recommend giving PinPong a try?

If you have previously used the RPi.GPIO library, I suggest exploring PinPong. You need not worry about the coding complexities for your creative projects, as there are pre-defined reading methods available for a wide range of sensors. This greatly reduces the difficulty of coding for your project.

If you have a foundation in Python coding but have mainly worked on PCs thus far, it might be worth considering integrating hardware control. By combining the power of PinPong library, your understanding of hardware will be significantly simplified, enabling you to swiftly implement projects through library functions.If anyone has made new discoveries regarding Python libraries for the Raspberry Pi or has innovative ideas based on PinPong, I encourage open discussions and exchanges.