SEARCH
TOOLBOX
LANGUAGES
modified on 17 August 2010 at 17:31 ••• 43,174 views

Blinky, Button & GPIO examples using Python

From Manuals

Jump to: navigation, search

Contents

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 sys
import time

print "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 sys
import time

print "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 sys
import time
import re

def 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 32
PIOA 0 set as Input
electrum100:/home/python# set-gpio 55
PIOA 23 set as Input

Before Connecting the Short cable between PA0 and PA23

electrum100:/home/python# python gpio1.py 32 55
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

        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 : 1

The value on the PIN 55 is : 0

After connecting the Short cable between PA0 and PA23

electrum100:/home/python# python gpio1.py 32 55
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

        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 : 1

The 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