树莓派安装Python
删除旧版本的Python2.7
sudo apt-get autoremove python2.7
sudo rm /usr/bin/python
sudo rm /usr/bin/pip
安装Python3
# 安装python3
sudo apt-get install python3-dev
调整python命令指向(不建议)
我们可以在树莓派上将python命令指向python3:
sudo ln -s /usr/bin/python3.7 /usr/bin/python
但是,实际使用中,目前为止我还是不推荐这样的改动。因为在实践中我遇到了很多由此引起的不必要的问题。我的建议是,要使用python3时,使用python3命令。
安装pip
#Python2和Python3各自有自己的pip模块
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
sudo python get-pip.py
sudo python3 get-pip.py
# 使用apt-get安装pip(安装在python2的dist-packages下)、安装pip3(安装在python3的dist-packages下)
sudo apt-get install python-pip
sudo apt-get install python3-pip
# 使用easy_install模块安装pip(安装在python2的dist-packages下)、安装pip3(安装在python3的dist-packages下)
sudo python -m easy_install pip
sudo python3 -m easy_install pip
安装VSCode
RPi.GPIO 模块
导入模块
import RPi.GPIO as GPIO
针脚编号
参考链接:
树莓派基础
GPIO.setmode(GPIO.BOARD)
# or
GPIO.setmode(GPIO.BCM)
配置通道
配置通道channel为输入
GPIO.setup(channel, GPIO.IN)
配置channel为输出
GPIO.setup(channel, GPIO.OUT)
GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) #指定输出通道的初始值
配置多个通道
chan_list = [11,12] # add as many channels as you want!
# you can tuples instead i.e.:
# chan_list = (11,12)
GPIO.setup(chan_list, GPIO.OUT)
输入
读取channel针脚的值:
GPIO.input(channel)
返回值:0/GPIO.LOW/False 1/GPIO.HIGH/TRUE
输出
设置GPIO针脚的输出状态
GPIO.output(channel, state)
state 可以为 0 / GPIO.LOW / False 或者 1 / GPIO.HIGH / True。
设置多个针脚的输出状态
chan_list = [11,12] # also works with tuples
GPIO.output(chan_list, GPIO.LOW) # sets all to GPIO.LOW
GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # sets first HIGH and second LOW
清理
在任何程序结束后,请养成清理用过的资源的好习惯。使用 RPi.GPIO 也同样需要这样。恢复所有使用过的通道状态为输入,您可以避免由于短路意外损坏您的 Raspberry Pi 针脚。注意,该操作仅会清理您的脚本使用过的 GPIO 通道。
GPIO.cleanup()
使用PWM
创建PWM实例
p = GPIO.PWM(channel, frequency)
启用PWM
p.start(dc) # where dc is the duty cycle (0.0 <= dc <= 100.0)
更改占空比
p.ChangeDutyCycle(dc) # where 0.0 <= dc <= 100.0
停止PWM
p.stop()
例程:
- LED每两秒闪烁一次 ```python import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 0.5) p.start(1) input(‘Press return to stop:’) # use raw_input for Python 2 p.stop() GPIO.cleanup()
2. LED在亮暗之间切换
```python
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 50) # 通道为 12 频率为 50Hz
p.start(0)
try:
while 1:
for dc in range(0, 101, 5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
for dc in range(100, -1, -5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
except KeyboardInterrupt:
pass
p.stop()
GPIO.cleanup()