If you want to play with hardware control, the Raspberry Pi is definitely a good choice. This credit card-sized computer board, paired with Python, allows you to easily achieve various hardware interactions. Whether it’s lighting up an LED or controlling a motor, it’s all possible. Today, let’s talk about how to use Python to do things on the Raspberry Pi.
1.
What is GPIO
GPIO (General Purpose Input/Output) is essentially the pins on the Raspberry Pi that can connect to external hardware. They act like the hands and feet of the Raspberry Pi, capable of receiving external signals and outputting control signals. To control these pins with Python, you need to install the RPi.GPIO
module:
import RPi.GPIO as GPIO
# Set the pin numbering mode
GPIO.setmode(GPIO.BCM)
# Set pin 18 to output mode
GPIO.setup(18, GPIO.OUT)
Tip: 💡 GPIO pins have two numbering schemes: BCM and BOARD. BCM uses the chip’s pin numbering, while BOARD uses the physical position numbering. It is recommended to use BCM for more intuitive coding.
2.
LED Blinking
Let’s do the simplest example to make the LED blink. Connect the positive terminal of the LED to GPIO 18 and the negative terminal to ground (GND). Here’s the code:
import RPi.GPIO as GPIO
import time
led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
try:
while True:
GPIO.output(led_pin, GPIO.HIGH) # On
time.sleep(0.5)
GPIO.output(led_pin, GPIO.LOW) # Off
time.sleep(0.5)
except KeyboardInterrupt:
GPIO.cleanup() # Clean up
The code does something quite simple: it alternates the LED on and off every half second. GPIO.HIGH
powers the pin, while GPIO.LOW
turns it off. Finally, using a try-except
structure allows for a clean exit from the program by pressing Ctrl+C.
3.
Button Interaction
Having only output is boring, so let’s add a button to play with input signals. Connect one end of the button to GPIO 17 and the other end to ground:
import RPi.GPIO as GPIO
import time
button_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
while True:
if GPIO.input(button_pin) == GPIO.LOW:
print("Button pressed!")
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup()
Tip: 💡 GPIO.PUD_UP
is an internal pull-up resistor that keeps the button at a high level when not pressed, and low when pressed. This helps avoid fluctuating signals.
4.
PWM Dimming
PWM (Pulse Width Modulation) sounds advanced, but it’s actually just rapidly turning the LED on and off to adjust brightness. It’s like quickly blocking your eyes with your hand, making it seem like you’re adjusting the light:
import RPi.GPIO as GPIO
import time
led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
pwm = GPIO.PWM(led_pin, 100) # 100Hz frequency
pwm.start(0) # Start with 0 duty cycle
try:
while True:
# Gradually brighten
for dc in range(0, 101, 5):
pwm.ChangeDutyCycle(dc)
time.sleep(0.1)
# Gradually dim
for dc in range(100, -1, -5):
pwm.ChangeDutyCycle(dc)
time.sleep(0.1)
except KeyboardInterrupt:
pwm.stop()
GPIO.cleanup()
5.
Temperature Sensor Play
The DHT11 temperature sensor is a cheap and easy-to-use gadget. Just install the Adafruit_DHT
module to use it:
import Adafruit_DHT
import time
sensor = Adafruit_DHT.DHT11
pin = 4 # DHT11 connected to GPIO 4
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print(f'Temperature: {temperature:.1f}°C, Humidity: {humidity:.1f}%')
else:
print('Failed to read, try again...')
time.sleep(2)
These are the basics of controlling the Raspberry Pi with Python. GPIO is the bridge for interacting with the outside world, capable of handling input/output and digital/analog signals. Remember to use cleanup() after using the pins; otherwise, unexpected situations may occur. The most important thing in hardware control is to get hands-on experience. Watching the LED light up and the button respond brings a great sense of achievement.
Recommended Reading
1. Python Audio Processing: Create Your Own Music 2. Python Asynchronous Programming: Improve Program Performance 3. MongoDB: Python for Document Databases