用python 控制gpio

來源:互聯網
上載者:User
Blinky, Button & GPIO examples using Python
Contents

[hide]

  • 1 Examples using Python
    • 1.1 Blinky Example
    • 1.2 Button Example
    • 1.3 GPIO Example


Examples using Python

The following application note covers the use of Electrum100's peripherals using Python. SYSFS method is used to access the GPIO's. To create the interfaces for GPIO's under /sys/class/gpio/*, the following configuration has to be enabled in the board configuration file

CONFIG_GPIO_SYSFS=y

Blinky Example

User LED is connected to GPIO PA30. An interface for the user LED is created in the kernel by adding the following code in board-electrum-100.c

/* * LEDs */static struct gpio_led ek_leds[] = {{/* led1, yellow */.name= "ds1",.gpio= AT91_PIN_PA25,.default_trigger= "heartbeat",},{/* led2, green */.name= "ds2",.gpio= AT91_PIN_PA30,//.active_low= 1,.default_trigger= "none",}};

And add the following lines in ek_board_init()

/* LEDs */at91_gpio_leds(ek_leds, ARRAY_SIZE(ek_leds));

Python script for Blinky Example:

import sysimport timeprint "Blinking User LED"print "Enter CTRL+C to exit"def ledon():        value = open("/sys/class/leds/ds2/brightness","w")        value.write(str(1))        value.close()def ledoff():        value = open("/sys/class/leds/ds2/brightness","w")        value.write(str(0))        value.close()while True:        ledon()        time.sleep(.5)        ledoff()        time.sleep(.5)

Button Example

In Electrum100, GPIO PA31 is used for the User Button.

import sysimport timeprint "Button Example"print "Press CTRL + C to exit"def pins_export():        try:                pin1export = open("/sys/class/gpio/export","w")                pin1export.write(str(63))                pin1export.close()        except IOError:                print "INFO: GPIO 63 already Exists, skipping export gpio"def read_button():        fp1 = open("/sys/class/gpio/gpio63/value","r")        value = fp1.read()        return value        fp1.close()def write_led(value):        fp2 =  open("/sys/class/leds/ds2/brightness","w")        fp2.write(str(value))        fp2.close()pins_export()while True:        button_value =  read_button()        write_led(button_value)

GPIO Example

The following example allows the user to set a selected GPIO pin as an Input or Output and read the values from the pins configured. As some of the GPIO's have alternate Functions, it is required that, pins have to be initialized as GPIO's before executing the following test example. set-gpio is a C-binary that initializes a single pin at a time. (Default as Input Pin)

import sysimport timeimport redef setpins(pin_no, pin_direction):        gpioopnum = "gpio%s" % (str(pin_no), )        pin1dir = open("/sys/class/gpio/"+gpioopnum+"/direction","w")        if pin_direction == 1:                pin1dir.write("high")        else:                pin1dir.write("in")        pin1dir.close()def readpins(pin_no):        gpioopnum = "gpio%s" % (str(pin_no), )        pin1val = open("/sys/class/gpio/"+gpioopnum+"/value","r")        output = pin1val.read()        print "The value on the PIN %s is : %s" % (str(pin_no), str(output))        pin1val.close()def unexport_pins(pins):        try:                fp4 = open("/sys/class/gpio/unexport","w")                fp4.write(str(pins))                fp4.close()        except IOError:                print "GPIO %s is not found, so skipping unexport gpio" % (str(pins), )def export_pins(pins):        try:                fp1 = open("/sys/class/gpio/export","w")                fp1.write(str(pins))                fp1.close()        except IOError:                print "GPIO %s already Exists, so skipping export gpio" % (str(pins), )print "Warning: Make sure that C-binary to Initialize GPIO's is executed prior to this. The script may not work as intended if the Ports are not initialized properly"+"\n"for i in range(1 , len(sys.argv)):        export_pins(sys.argv[i]) direction = raw_input(" Configure PIN %s as OUTPUT(1) / INPUT(2) ?: " % (str(sys.argv[i]), ))        setpins(sys.argv[i], int(direction))print "\n"+"            Reading PIN values....."for i in range(1 , len(sys.argv)):        readpins(sys.argv[i])for i in range(1 , len(sys.argv) ):        unexport_pins(sys.argv[i])

Procedure:

electrum100:/home/python# set-gpio 32PIOA 0 set as Inputelectrum100:/home/python# set-gpio 55PIOA 23 set as Input

Before Connecting the Short cable between PA0 and PA23

electrum100:/home/python# python gpio1.py 32 55Warning: Make sure that C-binary to initialize GPIO's is executed prior to this. The script may not work as intended if the Ports are not initialized properly        Configure PIN 32 as OUTPUT(1) / INPUT(2) ?: 1        Configure PIN 55 as OUTPUT(1) / INPUT(2) ?: 2                Reading PIN values.....The value on the PIN 32 is : 1The value on the PIN 55 is : 0

After connecting the Short cable between PA0 and PA23

electrum100:/home/python# python gpio1.py 32 55Warning: Make sure that C-binary to initialize GPIO's is executed prior to this. The script may not work as intended if the Ports are not initialized properly        Configure PIN 32 as OUTPUT(1) / INPUT(2) ?: 1        Configure PIN 55 as OUTPUT(1) / INPUT(2) ?: 2                Reading PIN values.....The value on the PIN 32 is : 1The value on the PIN 55 is : 1

The convention used to represent the Pin numbers using SYSFS procedure is explained with examples.

 PA Base - 32 PB Base - 64 PC Base - 96 Ex: To initialize PA1, use PA-Base + 1 = 32 + 1 = 33                  PA31, use 32 + 31 = 63                  PB0, use PB-Base + 0 = 64 + 0 = 64                  PC10, use 96 + 10 = 106
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.