导入RPI.GPIO库:
import RPi.GPIO as GPIO
设置引脚模式:
GPIO.setmode(GPIO.BMC/BOARD) #BCM/BOARD两种模式
检测已设置的模式:
mode = GPIO.getmode()
设置引脚输入输出:
GPIO.setup(Pin,GPIO.IN) #设置为输入
GPIO.setup(Pin,GPIO.OUT) #设置为输出
设置初始化电平:
GPIO.setup(Pin,GPIO.OUT,initial=GPIO.HIGH) #初始化为高电平
GPIO.setup(Pin,GPIO.OUT,initial=GPIO.LOW) #初始化为低电平
GPIO读取与输出:
#读取
GPIO.input(Pin)
#输出
GPIO.output(Pin,1/0)
以列表形式批量设置引脚:
#设置引脚模式
PinList=[Pin1,Pin2,Pin3]
GPIO.setup(PinList,GPIO.IN)
#设置输出电平
PinList = [Pin1,Pin2]
GPIO.output(PinList, GPIO.LOW)
GPIO.output(PinList, (GPIO.HIGH, GPIO.LOW))
设置上拉下拉电阻:
#设置上拉下拉电阻
GPIO.setup(Pin,GPIO.IN,pull_up_down=GPIO.PUD_UP/GPIO.DOWN)
设置中断:
#wait_for_edge()
#例子:
#边缘检测,上升沿,延时5s
channel = GPIO.wait_for_edge(channel, GPIO_RISING, timeout=5000)
if channel is None:
print('Timeout occurred')
else:
print('Edge detected on channel', channel)
#add_event_detect()
#实例
GPIO.add_event_detect(channel, GPIO.RISING)
do_something()
if GPIO.event_detected(channel):
print('Button pressed')
#Threaded回调
#实例:
def my_callback(channel):
print('This is a edge event callback function!')
print('Edge detected on channel %s'%channel)
print('This is run in a different thread to your main program')
GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback)
#删除检测
GPIO.remove_event_detect(channel)
设置PWM:
Pwm=GPIO.PWM(pin,frequence) #创建PWM实例
Pwm.start(dc) #启动PWM dc值(0.0<dc<100.0)
Pwm.ChangeFrequency(freq) #改变PWM频率
Pwm.ChangeDutyCycle(dc) #改变PWM的占空比0.0<=dc <=100.
Pwm.stop() #停止PWM
恢复GPIO:
GPIO.cleanup() #恢复全部
GPIO.cleanup(channel) #恢复单个
GPIO.cleanup( (channel1, channel2) ) #以列表和元组批量恢复
GPIO.cleanup( [channel1, channel2] )