The Raspberry Pi is a microcomputer that can interact with various electronic components through GPIO pins. Today we will learn how to use Python’s RPi.GPIO module to control these GPIO pins for hardware control. Whether you want to create smart home devices or DIY electronic projects, this is a very practical lesson.
First, you need to install the RPi.GPIO library on the Raspberry Pi. Open the terminal and enter the following commands:
sudo apt-get update
sudo apt-get install python-rpi.gpio python3-rpi.gpio
Once the installation is complete, we can start writing Python code to control the GPIO. Before we begin, let’s understand two important concepts:
GPIO Numbering MethodThe GPIO pins on the Raspberry Pi have two numbering methods:
-
BCM numbering: uses the actual GPIO number -
BOARD numbering: uses the physical pin position number
It is recommended to use BCM numbering as it more intuitively reflects the actual GPIO numbering. Set it in the code like this:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # Set BCM numbering method
Let’s start with the simplest LED control. Here is a complete code to make an LED blink:
import RPi.GPIO as GPIO
import time
# Set GPIO pin number
LED_PIN = 18
# Initialize GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT) # Set to output mode
try:
while True:
GPIO.output(LED_PIN, GPIO.HIGH) # Output high level, LED on
print("LED is ON")
time.sleep(1) # Pause for 1 second
GPIO.output(LED_PIN, GPIO.LOW) # Output low level, LED off
print("LED is OFF")
time.sleep(1) # Pause for 1 second
except KeyboardInterrupt:
print("\nProgram has stopped")
finally:
GPIO.cleanup() # Clean up GPIO resources
Code Explanation:
-
Import necessary modules: RPi.GPIO for controlling GPIO, time for implementing delays -
Set the GPIO pin number connected to the LED (here we use pin 18) -
Initialize GPIO and set it to output mode -
In a loop, alternate between high and low levels to make the LED blink -
Use try-except structure to handle exiting with Ctrl+C -
Finally, use GPIO.cleanup() to release resources
For a more advanced implementation, let’s implement voice control for the LED. First, install the speech recognition library:
pip3 install SpeechRecognition
Here is the complete voice-controlled LED program:
import RPi.GPIO as GPIO
import speech_recognition as sr
import time
# Initialize speech recognizer
r = sr.Recognizer()
# LED control function
def control_led(command):
if 'turn on light' in command:
GPIO.output(18, GPIO.HIGH)
print("LED is ON")
elif 'turn off light' in command:
GPIO.output(18, GPIO.LOW)
print("LED is OFF")
# GPIO initialization
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
try:
with sr.Microphone() as source:
print("Waiting for voice command...")
while True:
audio = r.listen(source)
try:
text = r.recognize_google(audio, language='zh-CN')
print(f"Recognized command: {text}")
control_led(text)
except sr.UnknownValueError:
print("Unable to recognize speech")
except sr.RequestError as e:
print(f"Speech recognition service error: {e}")
except KeyboardInterrupt:
print("\nProgram has stopped")
finally:
GPIO.cleanup()
Here are some practical tips for GPIO programming:
-
Always remember to use GPIO.cleanup() to clean up resources, preferably in the finally block -
Use try-except to handle exceptions, making the program more stable -
To prevent high CPU usage, add short delays in the loop -
Immediately set the pin mode after setting the GPIO mode to avoid confusion -
Use variables to store pin numbers for easy modification later
Common pitfalls:
-
Forgetting to run the program with sudo (GPIO operations require root permissions) -
Mixing BCM and BOARD numbering methods -
Not properly cleaning up GPIO resources -
Connecting the wrong pin causing a short circuit
By now, you have learned the basics of controlling the Raspberry Pi’s GPIO with Python. Give it a try, starting with lighting up an LED, and gradually you will be able to create more complex hardware control projects. Remember: the most important part of programming is practice; theory alone is not enough, and writing and debugging are key to progress.
If you want to learn more, you can try:
-
Controlling multiple LEDs to achieve a running light effect -
Reading button input states -
Controlling servos or stepper motors -
Reading data from various sensors
Have fun! Remember to pay attention to electrical safety when working with hardware.