树莓派自带thonny
点亮LED灯
import RPi.GPIO as GPIO
import time
# 设置GPIO模式为BCM
GPIO.setmode(GPIO.BCM)
# 设置LED引脚
led_pin = 18
# 设置LED引脚为输出
GPIO.setup(led_pin, GPIO.OUT)
# 点亮LED
GPIO.output(led_pin, GPIO.HIGH)
# 延时2秒
time.sleep(2)
# 关闭LED
GPIO.output(led_pin, GPIO.LOW)
# 清理GPIO设置
GPIO.cleanup()
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
try:
while True:
GPIO.output(11, True) # 将 GPIO11 引脚设置为高电平
time.sleep(1) # 持续一秒
GPIO.output(11, False) # 将 GPIO11 引脚设置为低电平
time.sleep(1) # 持续一秒
except KeyboardInterrupt:
GPIO.cleanup() # 清除 GPIO 引脚并退出应用
示例:读取DHT22温湿度传感器数据
import Adafruit_DHT
# 指定传感器型号和GPIO引脚
sensor = Adafruit_DHT.DHT22
pin = 4
# 读取温湿度数据
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print(f"温度={temperature:0.1f}°C,湿度={humidity:0.1f}%")
else:
print("读取传感器数据失败")
示例:控制舵机
import RPi.GPIO as GPIO
import time
# 设置GPIO模式为BCM
GPIO.setmode(GPIO.BCM)
# 设置舵机引脚
servo_pin = 17
# 设置舵机引脚为输出
GPIO.setup(servo_pin, GPIO.OUT)
# 创建PWM对象
pwm = GPIO.PWM(servo_pin, 50)
# 将舵机转动到90度位置
pwm.start(7.5)
time.sleep(2)
# 将舵机转动到0度位置
pwm.ChangeDutyCycle(2.5)
time.sleep(2)
# 停止PWM
pwm.stop()
# 清理GPIO设置
GPIO.cleanup()