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.
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:
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.
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.
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.
Figure: Hardware diagram of the Blink project
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.
RPi.GPIO:https://pypi.org/project/RPi.GPIO/#description
Figure: Raspberry Pi Pin Definition Chart
#import the GPIO and time package
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(4, GPIO.OUT)
# loop through 50 times, on/off for 1 second
for i in range(50):
GPIO.output(4,True)
time.sleep(1)
GPIO.output(4,False)
time.sleep(1)
GPIO.cleanup()
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
Board("rpi").begin()
led = Pin(Pin.D4, Pin.OUT)
while True:
led.write_digital(1)
time.sleep(2)
led.write_digital(0)
time.sleep(1)
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.
Upon comparing the official descriptions and conducting actual tests, I have discovered that both libraries can achieve several basic functionalities, including:
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.
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:
Hardware:
System environment:
Hardware Connection Diagram:
Connect the I2C interface ultrasonic sensor to the Raspberry Pi's I2C interface.
Figure: Raspberry Pi Hardware Connection Diagram
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:
Refer to the product's Wiki documentation to confirm the existence of a library specifically designed for the ultrasonic sensor used.
Install and import the appropriate library for the ultrasonic sensor mentioned in the Wiki documentation.
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
sys.path.append("../")
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)
time.sleep(0.1)
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:
Figure: Ultrasonic Distance Meter Project Demo
python
import pinpong
print(pinpong.__path__)
exit()
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库
Board("RPi").begin()
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)
time.sleep(0.5)
Figure: Ultrasonic Distance Meter Project Demo
Through this ultrasonic rangefinder project, it can be observed that RPi.GPIO and smbus libraries have certain limitations:
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:
Points of differentiation:
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:
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.
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
Python
#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.
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
lcd.set_cursor(5,1)
lcd.print(str(tem))
lcd.print('C')
time.sleep(1)
The current list of module libraries supported by PinPong includes:
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.
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.