GPIO 使用手册

Rpi GPIO 使用手册


RPi.GPIO Installation

Raspbian Wheezy

The RPi.GPIO module is installed by default in Raspbian. To make sure that it is at the latest version:

$ sudo apt-get update
$ sudo apt-get install python-rpi.gpio python3-rpi.gpio

To install the latest development version from the project source code library:

$ sudo apt-get install python-dev python3-dev
$ sudo apt-get install mercurial
$ sudo apt-get install python-pip python3-pip
$ sudo apt-get remove python-rpi.gpio python3-rpi.gpio
$ sudo pip install hg+http://hg.code.sf.net/p/raspberry-gpio-python/code#egg=RPi.GPIO
$ sudo pip-3.2 install hg+http://hg.code.sf.net/p/raspberry-gpio-python/code#egg=RPi.GPIO

To revert back to the default version in Raspbian:

$ sudo pip uninstall RPi.GPIO
$ sudo pip-3.2 uninstall RPi.GPIO
$ sudo apt-get install python-rpi.gpio python3-rpi.gpio

Other Distributions

It is recommended that you install RPi.GPIO using the pip utility as superuser (root):

# pip install RPi.GPIO


Raspberry Pi / BCM2835 Technical Reference

Detailed technical reference can be found at:

Note that RPi pins 3 and 5 (Rev2 and B+ GPIO 02 and 03, Rev1 - GPIO 00 and 01) have 1K8 pull-up resistors to 3v3.


Examples

RPi.GPIO module basics

Importing the module

To import the RPi.GPIO module:

import RPi.GPIO as GPIO

By doing it this way, you can refer to it as just GPIO through the rest of your script.

To import the module and check to see if it is successful:

try:
    import RPi.GPIO as GPIO
except RuntimeError:
    print("Error importing RPi.GPIO!  This is probably because you need superuser privileges.  You can achieve this by using 'sudo' to run your script")

Pin numbering

There are two ways of numbering the IO pins on a Raspberry Pi within RPi.GPIO. The first is using the BOARD numbering system. This refers to the pin numbers on the P1 header of the Raspberry Pi board. The advantage of using this numbering system is that your hardware will always work, regardless of the board revision of the RPi. You will not need to rewire your connector or change your code.

The second numbering system is the BCM numbers. This is a lower level way of working - it refers to the channel numbers on the Broadcom SOC. You have to always work with a diagram of which channel number goes to which pin on the RPi board. Your script could break between revisions of Raspberry Pi boards.

To specify which you are using using (mandatory):

GPIO.setmode(GPIO.BOARD)
  # or
GPIO.setmode(GPIO.BCM)

To detect which pin numbering system has been set (for example, by another Python module):

mode = GPIO.getmode()

The mode will be GPIO.BOARD, GPIO.BCM or None

Warnings

It is possible that you have more than one script/circuit on the GPIO of your Raspberry Pi. As a result of this, if RPi.GPIO detects that a pin has been configured to something other than the default (input), you get a warning when you try to configure a script. To disable these warnings:

GPIO.setwarnings(False)

Setup up a channel

You need to set up every channel you are using as an input or an output. To configure a channel as an input:

GPIO.setup(channel, GPIO.IN)

(where channel is the channel number based on the numbering system you have specified (BOARD or BCM)).

More advanced information about setting up input channels can be found here.

To set up a channel as an output:

GPIO.setup(channel, GPIO.OUT)

(where channel is the channel number based on the numbering system you have specified (BOARD or BCM)).

You can also specify an initial value for your output channel:

GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH)

Setup more than one channel

You can set up more than one channel per call (release 0.5.8 onwards). For example:

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)

Input

To read the value of a GPIO pin:

GPIO.input(channel)

(where channel is the channel number based on the numbering system you have specified (BOARD or BCM)). This will return either 0 / GPIO.LOW / False or 1 / GPIO.HIGH / True.

Output

To set the output state of a GPIO pin:

GPIO.output(channel, state)

(where channel is the channel number based on the numbering system you have specified (BOARD or BCM)).

State can be 0 / GPIO.LOW / False or 1 / GPIO.HIGH / True.

Output to several channels

You can output to many channels in the same call (release 0.5.8 onwards). For example:

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

Cleanup

At the end any program, it is good practice to clean up any resources you might have used. This is no different with RPi.GPIO. By returning all channels you have used back to inputs with no pull up/down, you can avoid accidental damage to your RPi by shorting out the pins. Note that this will only clean up GPIO channels that your script has used. Note that GPIO.cleanup() also clears the pin numbering system in use.

To clean up at the end of your script:

GPIO.cleanup()

It is possible that don't want to clean up every channel leaving some set up when your program exits. You can clean up individual channels, a list or a tuple of channels:

GPIO.cleanup(channel)
GPIO.cleanup( (channel1, channel2) )
GPIO.cleanup( [channel1, channel2] )

RPi Board Information and RPi.GPIO version

To discover information about your RPi:

GPIO.RPI_INFO

To discover the Raspberry Pi board revision:

GPIO.RPI_INFO['P1_REVISION']
GPIO.RPI_REVISION    (deprecated)

To discover the version of RPi.GPIO:

GPIO.VERSION

Inputs

There are several ways of getting GPIO input into your program. The first and simplest way is to check the input value at a point in time. This is known as 'polling' and can potentially miss an input if your program reads the value at the wrong time. Polling is performed in loops and can potentially be processor intensive. The other way of responding to a GPIO input is using 'interrupts' (edge detection). An edge is the name of a transition from HIGH to LOW (falling edge) or LOW to HIGH (rising edge).

Pull up / Pull down resistors

If you do not have the input pin connected to anything, it will 'float'. In other words, the value that is read in is undefined because it is not connected to anything until you press a button or switch. It will probably change value a lot as a result of receiving mains interference.

To get round this, we use a pull up or a pull down resistor. In this way, the default value of the input can be set. It is possible to have pull up/down resistors in hardware and using software. In hardware, a 10K resistor between the input channel and 3.3V (pull-up) or 0V (pull-down) is commonly used. The RPi.GPIO module allows you to configure the Broadcom SOC to do this in software:

GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  # or
GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

(where channel is the channel number based on the numbering system you have specified - BOARD or BCM).

Testing inputs (polling)

You can take a snapshot of an input at a moment in time:

if GPIO.input(channel):
    print('Input was HIGH')
else:
    print('Input was LOW')

To wait for a button press by polling in a loop:

while GPIO.input(channel) == GPIO.LOW:
    time.sleep(0.01)  # wait 10 ms to give CPU chance to do other things

(this assumes that pressing the button changes the input from LOW to HIGH)

Interrupts and Edge detection

An edge is the change in state of an electrical signal from LOW to HIGH (rising edge) or from HIGH to LOW (falling edge). Quite often, we are more concerned by a change in state of an input than it's value. This change in state is an event.

To avoid missing a button press while your program is busy doing something else, there are two ways to get round this:

wait_for_edge() function

  • the wait_for_edge() function
  • the event_detected() function
  • a threaded callback function that is run when an edge is detected
  • The wait_for_edge() function is designed to block execution of your program until an edge is detected. In other words, the example above that waits for a button press could be rewritten as:
  • GPIO.wait_for_edge(channel, GPIO.RISING)
    
  • Note that you can detect edges of type GPIO.RISING, GPIO.FALLING or GPIO.BOTH. The advantage of doing it this way is that it uses a negligible amount of CPU, so there is plenty left for other tasks.
  • If you only want to wait for a certain length of time, you can use the timeout parameter:
  • # wait for up to 5 seconds for a rising edge (timeout is in milliseconds)
    channel = GPIO.wait_for_edge(channel, GPIO_RISING, timeout=5000)
    if channel is None:
        print('Timeout occurred')
    else:
        print('Edge detected on channel', channel)
    

    event_detected() function

    The event_detected() function is designed to be used in a loop with other things, but unlike polling it is not going to miss the change in state of an input while the CPU is busy working on other things. This could be useful when using something like Pygame or PyQt where there is a main loop listening and responding to GUI events in a timely basis.

    GPIO.add_event_detect(channel, GPIO.RISING)  # add rising edge detection on a channel
    do_something()
    if GPIO.event_detected(channel):
        print('Button pressed')
    

    Note that you can detect events for GPIO.RISING, GPIO.FALLING or GPIO.BOTH.

    Threaded callbacks

    RPi.GPIO runs a second thread for callback functions. This means that callback functions can be run at the same time as your main program, in immediate response to an edge. For example:

    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)  # add rising edge detection on a channel
    ...the rest of your program...
    

    If you wanted more than one callback function:

    def my_callback_one(channel):
        print('Callback one')
    
    def my_callback_two(channel):
        print('Callback two')
    
    GPIO.add_event_detect(channel, GPIO.RISING)
    GPIO.add_event_callback(channel, my_callback_one)
    GPIO.add_event_callback(channel, my_callback_two)
    

    Note that in this case, the callback functions are run sequentially, not concurrently. This is because there is only one thread used for callbacks, in which every callback is run, in the order in which they have been defined.

    Switch debounce

    You may notice that the callbacks are called more than once for each button press. This is as a result of what is known as 'switch bounce'. There are two ways of dealing with switch bounce:

    • add a 0.1uF capacitor across your switch.
    • software debouncing
    • a combination of both

    To debounce using software, add the bouncetime= parameter to a function where you specify a callback function. Bouncetime should be specified in milliseconds. For example:

    # add rising edge detection on a channel, ignoring further edges for 200ms for switch bounce handling
    GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback, bouncetime=200)
    

    or

    GPIO.add_event_callback(channel, my_callback, bouncetime=200)
    

    Remove event detection

    If for some reason, your program no longer wishes to detect edge events, it is possible to stop them:

    GPIO.remove_event_detect(channel)
来源: raspberry-gpio-python / Wiki / Inputs

GPIO Outputs

1. First set up RPi.GPIO (as described here)

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

2. To set an output high:

GPIO.output(12, GPIO.HIGH)
 # or
GPIO.output(12, 1)
 # or
GPIO.output(12, True)

3. To set an output low:

GPIO.output(12, GPIO.LOW)
 # or
GPIO.output(12, 0)
 # or
GPIO.output(12, False)

4. To output to several channels at the same time:

chan_list = (11,12)
GPIO.output(chan_list, GPIO.LOW) # all LOW
GPIO.output(chan_list, (GPIO.HIGH,GPIO.LOW))  # first LOW, second HIGH

5. Clean up at the end of your program

GPIO.cleanup()

Note that you can read the current state of a channel set up as an output using the input() function. For example to toggle an output:

GPIO.output(12, not GPIO.input(12))
 

Using PWM in RPi.GPIO

To create a PWM instance:

p = GPIO.PWM(channel, frequency)

To start PWM:

p.start(dc)   # where dc is the duty cycle (0.0 <= dc <= 100.0)

To change the frequency:

p.ChangeFrequency(freq)   # where freq is the new frequency in Hz

To change the duty cycle:

p.ChangeDutyCycle(dc)  # where 0.0 <= dc <= 100.0

To stop PWM:

p.stop()

Note that PWM will also stop if the instance variable 'p' goes out of scope.

An example to blink an LED once every two seconds:

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

An example to brighten/dim an LED:

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p = GPIO.PWM(12, 50)  # channel=12 frequency=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()
 

gpio_function(channel)

Shows the function of a GPIO channel.
For example:

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
func = GPIO.gpio_function(pin)

will return a value from:
GPIO.IN, GPIO.OUT, GPIO.SPI, GPIO.I2C, GPIO.HARD_PWM, GPIO.SERIAL, GPIO.UNKNOWN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值