GPIO and Electronics
The GPIO header
The 40-pin header provides power (3.3 V and 5 V), ground and general-purpose input/output pins, plus I²C, SPI and UART buses. Run pinout on the Pi to see a diagram.
GPIO pins use 3.3 V logic and are not 5 V tolerant. Connecting 5 V signals can permanently damage the Pi. Use level shifters or voltage dividers for 5 V devices.
gpiozero
from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(2)
button.when_pressed = led.on
button.when_released = led.off
pause()
gpiozero handles pull-up resistors and debouncing, and offers classes for motion sensors, distance sensors, motors (through drivers) and more.
Sensors over I²C
Enable I²C with sudo raspi-config (Interface Options), then:
sudo apt install -y i2c-tools
i2cdetect -y 1 # lists device addresses, e.g. 0x76 for a BME280
import board
from adafruit_bme280 import basic as adafruit_bme280
i2c = board.I2C()
sensor = adafruit_bme280.Adafruit_BME280_I2C(i2c, address=0x76)
print(f"{sensor.temperature:.1f} °C, {sensor.humidity:.0f}% RH")
Motors and higher-power devices
As with Arduino: use driver boards, separate power supplies and a shared ground. Relays switching mains voltage should only be handled with proper, certified modules and enclosures, and preferably by someone qualified.
Camera
The Camera Module connects to the CSI port; the picamera2 library captures photos and video for time-lapses, security or computer-vision projects.
Exercise
Build a motion-triggered camera: a PIR sensor on GPIO triggers picamera2 to take a photo, saves it with a timestamp and logs the event, running as a systemd service.
Check yourself
- Why must you never feed 5 V into a GPIO pin?
- What does
i2cdetectshow? - What does gpiozero handle for you?
進捗はこのブラウザーにのみ保存されます。
レビューに提出(10 ポイント)