树莓派安装Python

删除旧版本的Python2.7

  1. sudo apt-get autoremove python2.7
  2. sudo rm /usr/bin/python
  3. sudo rm /usr/bin/pip

安装Python3

  1. # 安装python3
  2. sudo apt-get install python3-dev

调整python命令指向(不建议)

我们可以在树莓派上将python命令指向python3:

  1. sudo ln -s /usr/bin/python3.7 /usr/bin/python

但是,实际使用中,目前为止我还是不推荐这样的改动。因为在实践中我遇到了很多由此引起的不必要的问题。我的建议是,要使用python3时,使用python3命令。

安装pip

  1. #Python2和Python3各自有自己的pip模块
  2. curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
  3. sudo python get-pip.py
  4. sudo python3 get-pip.py
  5. # 使用apt-get安装pip(安装在python2的dist-packages下)、安装pip3(安装在python3的dist-packages下)
  6. sudo apt-get install python-pip
  7. sudo apt-get install python3-pip
  8. # 使用easy_install模块安装pip(安装在python2的dist-packages下)、安装pip3(安装在python3的dist-packages下)
  9. sudo python -m easy_install pip
  10. sudo python3 -m easy_install pip

安装VSCode

image.png

RPi.GPIO 模块

导入模块

  1. import RPi.GPIO as GPIO

针脚编号

参考链接:
树莓派基础

  1. GPIO.setmode(GPIO.BOARD)
  2. # or
  3. GPIO.setmode(GPIO.BCM)

配置通道

  • 配置通道channel为输入

    1. GPIO.setup(channel, GPIO.IN)
  • 配置channel为输出

    1. GPIO.setup(channel, GPIO.OUT)
    2. GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) #指定输出通道的初始值
  • 配置多个通道

    1. chan_list = [11,12] # add as many channels as you want!
    2. # you can tuples instead i.e.:
    3. # chan_list = (11,12)
    4. GPIO.setup(chan_list, GPIO.OUT)

    输入

    读取channel针脚的值:

    1. GPIO.input(channel)

    返回值:0/GPIO.LOW/False 1/GPIO.HIGH/TRUE

输出

  • 设置GPIO针脚的输出状态

    1. GPIO.output(channel, state)

    state 可以为 0 / GPIO.LOW / False 或者 1 / GPIO.HIGH / True。

  • 设置多个针脚的输出状态

    1. chan_list = [11,12] # also works with tuples
    2. GPIO.output(chan_list, GPIO.LOW) # sets all to GPIO.LOW
    3. GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # sets first HIGH and second LOW

    清理

    在任何程序结束后,请养成清理用过的资源的好习惯。使用 RPi.GPIO 也同样需要这样。恢复所有使用过的通道状态为输入,您可以避免由于短路意外损坏您的 Raspberry Pi 针脚。注意,该操作仅会清理您的脚本使用过的 GPIO 通道。

    1. GPIO.cleanup()

    使用PWM

  • 创建PWM实例

    1. p = GPIO.PWM(channel, frequency)
  • 启用PWM

    1. p.start(dc) # where dc is the duty cycle (0.0 <= dc <= 100.0)
  • 更改占空比

    1. p.ChangeDutyCycle(dc) # where 0.0 <= dc <= 100.0
  • 停止PWM

    1. p.stop()

例程:

  1. 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()

  1. 2. LED在亮暗之间切换
  2. ```python
  3. import time
  4. import RPi.GPIO as GPIO
  5. GPIO.setmode(GPIO.BOARD)
  6. GPIO.setup(12, GPIO.OUT)
  7. p = GPIO.PWM(12, 50) # 通道为 12 频率为 50Hz
  8. p.start(0)
  9. try:
  10. while 1:
  11. for dc in range(0, 101, 5):
  12. p.ChangeDutyCycle(dc)
  13. time.sleep(0.1)
  14. for dc in range(100, -1, -5):
  15. p.ChangeDutyCycle(dc)
  16. time.sleep(0.1)
  17. except KeyboardInterrupt:
  18. pass
  19. p.stop()
  20. GPIO.cleanup()