树莓派 - RPi.GPIO

本文介绍了RPi.GPIO模块,该模块允许用户通过Python控制Raspberry Pi的GPIO接口。文章详细解释了模块的工作原理,包括其如何利用Python/CAPI与底层硬件交互。此外,还提供了一个简单的Python脚本示例,展示如何使LED灯闪烁。

RPi.GPIO是通过Python/C API实现的,C代码操作底层寄存器, python通过Python/C API调用这些C接口。

这是关于RPi.GPIO项目的介绍。 其中提到了有python 垃圾回收机制,并不适合于实时要求的应用。

https://pypi.org/project/RPi.GPIO/

This package provides a class to control the GPIO on a Raspberry Pi.

Note that this module is unsuitable for real-time or timing critical applications. This is because you can not predict when Python will be busy garbage collecting. It also runs under the Linux kernel which is not suitable for real time applications - it is multitasking O/S and another process may be given priority over the CPU, causing jitter in your program. 


关于Python/C API,有点类似于JNI,PyObject  作为common object,用于参数和return

https://docs.python.org/3/c-api/intro.html

https://docs.python.org/3/c-api/structures.html#c.PyObjectPython


在树莓派中之前编译的系统,python, 以及RPi.GPIO module都已经预装了,

pi@raspberrypi:~/python $ python led.py 

执行python led.py脚本,LED闪烁。

#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import time

LED = 26

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED,GPIO.OUT)
try:
	while True:
		GPIO.output(LED,GPIO.HIGH)
		time.sleep(1)
		GPIO.output(LED,GPIO.LOW)
		time.sleep(1)
except:
	print("except")
	GPIO.cleanup()

下面是RPi.GPIO中 setmode的C代码

// python function setmode(mode)
static PyObject *py_setmode(PyObject *self, PyObject *args)
{
   int new_mode;

   if (!PyArg_ParseTuple(args, "i", &new_mode))
      return NULL;

   if (gpio_mode != MODE_UNKNOWN && new_mode != gpio_mode)
   {
      PyErr_SetString(PyExc_ValueError, "A different mode has already been set!");
      return NULL;
   }

   if (setup_error)
   {
      PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!");
      return NULL;
   }

   if (new_mode != BOARD && new_mode != BCM)
   {
      PyErr_SetString(PyExc_ValueError, "An invalid mode was passed to setmode()");
      return NULL;
   }

   if (rpiinfo.p1_revision == 0 && new_mode == BOARD)
   {
      PyErr_SetString(PyExc_RuntimeError, "BOARD numbering system not applicable on compute module");
      return NULL;
   }

   gpio_mode = new_mode;
   Py_RETURN_NONE;
}

PyMethodDef rpi_gpio_methods[] = {
   {"setup", (PyCFunction)py_setup_channel, METH_VARARGS | METH_KEYWORDS, "Set up a GPIO channel or list of channels with a direction and (optional) pull/up down control\nchannel        - either board pin number or BCM number depending on which mode is set.\ndirection      - IN or OUT\n[pull_up_down] - PUD_OFF (default), PUD_UP or PUD_DOWN\n[initial]      - Initial value for an output channel"},
   {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection\n[channel] - individual channel or list/tuple of channels to clean up.  Default - clean every channel that has been used."},
   {"output", py_output_gpio, METH_VARARGS, "Output to a GPIO channel or list of channels\nchannel - either board pin number or BCM number depending on which mode is set.\nvalue   - 0/1 or False/True or LOW/HIGH"},
   {"input", py_input_gpio, METH_VARARGS, "Input from a GPIO channel.  Returns HIGH=1=True or LOW=0=False\nchannel - either board pin number or BCM number depending on which mode is set."},
   {"setmode", py_setmode, METH_VARARGS, "Set up numbering mode to use for channels.\nBOARD - Use Raspberry Pi board numbers\nBCM   - Use Broadcom GPIO 00..nn numbers"},
   {"getmode", py_getmode, METH_VARARGS, "Get numbering mode used for channel numbers.\nReturns BOARD, BCM or None"},
   {"add_event_detect", (PyCFunction)py_add_event_detect, METH_VARARGS | METH_KEYWORDS, "Enable edge detection events for a particular GPIO channel.\nchannel      - either board pin number or BCM number depending on which mode is set.\nedge         - RISING, FALLING or BOTH\n[callback]   - A callback function for the event (optional)\n[bouncetime] - Switch bounce timeout in ms for callback"},
   {"remove_event_detect", py_remove_event_detect, METH_VARARGS, "Remove edge detection for a particular GPIO channel\nchannel - either board pin number or BCM number depending on which mode is set."},
   {"event_detected", py_event_detected, METH_VARARGS, "Returns True if an edge has occured on a given GPIO.  You need to enable edge detection using add_event_detect() first.\nchannel - either board pin number or BCM number depending on which mode is set."},
   {"add_event_callback", (PyCFunction)py_add_event_callback, METH_VARARGS | METH_KEYWORDS, "Add a callback for an event already defined using add_event_detect()\nchannel      - either board pin number or BCM number depending on which mode is set.\ncallback     - a callback function"},
   {"wait_for_edge", (PyCFunction)py_wait_for_edge, METH_VARARGS | METH_KEYWORDS, "Wait for an edge.  Returns the channel number or None on timeout.\nchannel      - either board pin number or BCM number depending on which mode is set.\nedge         - RISING, FALLING or BOTH\n[bouncetime] - time allowed between calls to allow for switchbounce\n[timeout]    - timeout in ms"},
   {"gpio_function", py_gpio_function, METH_VARARGS, "Return the current GPIO function (IN, OUT, PWM, SERIAL, I2C, SPI)\nchannel - either board pin number or BCM number depending on which mode is set."},
   {"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
   {NULL, NULL, 0, NULL}
};



<think> 我们先整理用户问题:用户明确询问“树莓派安装RPi.GPIO模块的方法”。 根据提供的引用信息,我们可以提取以下相关部分: 引用[3]中提到:“树莓派Raspberry Pi上安装和使用RPi.GPIO模块以及引脚对照表。2.测试是否安装成功,可以通过以下例子测试 pi@raspberrypi:~ $ python3 ... >>> import RPi.GPIO as GPIO” 虽然没有直接给出安装命令,但引用[3]的标题明确提到了“安装”,我们可以推断该引用内容应该包含安装方法。实际上,在树莓派系统中,RPi.GPIO通常是预装的,但如果没有,我们可以使用包管理器安装。 另外,引用[1]和[2]主要介绍了RPi.GPIO的功能和使用方法,对安装提及较少。 因此,我们主要参考引用[3]并补充常见的安装方法。 常见的安装方法: 1. 使用apt包管理器安装(适用于树莓派系统) 2. 使用pip安装 由于树莓派系统通常预装了Python,并且RPi.GPIO树莓派官方推荐的库,所以通常可以通过以下方式安装: 方法一:使用apt安装(推荐,因为可以安装系统依赖) sudo apt update sudo apt install python3-rpi.gpio # 用于Python3 # 或者安装Python2版本(如果系统有Python2) sudo apt install python-rpi.gpio 方法二:使用pip安装 pip install RPi.GPIO # 或者使用pip3 pip3 install RPi.GPIO 安装后,可以通过在Python解释器中导入模块来测试是否安装成功,如引用[3]所示: python3 >>> import RPi.GPIO as GPIO 另外,需要注意的是,如果使用虚拟环境,需要确保在正确的环境中安装。 根据上述分析,我们给出回答。 </think> 根据提供的引用信息,树莓派安装 RPi.GPIO 模块的方法如下: ### 安装步骤 1. **更新系统包列表** 首先确保系统包信息是最新的: ```bash sudo apt update ``` 2. **安装 RPi.GPIO 模块** 通过 APT 包管理器直接安装(Python 3 版本): ```bash sudo apt install python3-rpi.gpio ``` 或使用 pip 安装(兼容 Python 2/3): ```bash pip install RPi.GPIO ``` 3. **验证安装** 打开 Python 解释器测试导入模块(引用[3]): ```bash python3 >>> import RPi.GPIO as GPIO # 无报错即成功 ``` ### 补充说明 - RPi.GPIO树莓派**官方 GPIO 控制库**,通常预装在树莓派 OS 中,无需额外安装[^1][^3]。 - 如果遇到权限问题,需将用户加入 `gpio` 用户组: ```bash sudo usermod -aG gpio $USER ``` - 引脚编号模式建议使用 `GPIO.setmode(GPIO.BOARD)`(物理引脚编号),兼容所有树莓派型号[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值