public
Last active

BeagleBone GPIO with Python Test

  • Download Gist
bb-python-gpio-test.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#!/usr/bin/python
# time module is needed for sleep function:
import time
 
# Open up the pins and set mode in/out
# TODO: Error handling
setupPin = file("/sys/class/gpio/export", "w")
setupPin.write("%d" % (38))
setupPin.close()
 
setupPin = file("/sys/class/gpio/gpio38/direction", "w")
setupPin.write("out")
setupPin.close()
 
setupPin = file("/sys/class/gpio/export", "w")
setupPin.write("%d" % (70))
setupPin.close()
 
setupPin = file("/sys/class/gpio/gpio70/direction", "w")
setupPin.write("in")
setupPin.close()
 
#Open outPin for writing and inPin for reading:
outPin = file("/sys/class/gpio/gpio38/value", "w")
inPin = file("/sys/class/gpio/gpio70/value", "r")
 
try:
while True:
# This method uses polling to read the state of the pin.
# It's not the way it should be done, but we'll make do
# with this for now.
inPin.seek(0)
if inPin.read() =="1\n":
print "Button Pressed!\n"
outPin.write("1")
outPin.flush()
time.sleep(1)
 
outPin.write("0")
outPin.flush()
# don't peg the processor:
time.sleep(.1)
# Control+C will get us out of that loop and close the pins so that other apps can use:
except KeyboardInterrupt:
inPin = file("/sys/class/gpio/unexport", "w")
inPin.write("%d" % (38))
inPin.close()
 
outPin = file("/sys/class/gpio/unexport", "w")
outPin.write("%d" % (70))
inPin.close()

I'm just starting with Beaglebone GPIO, and I an wondering about when GPIO related files should be close()'ed.
In this code the outPin and inPin file handles, which are related to the /value files are never closed. Is that ok?
Does writing to the /unexport file for the GPIO eliminate the need for closing the /value files?
Thanks for any help with this, and thank you for posting this code.

Yes, the value file should be closed. This code is a little old and I abstracted these functions into a Python module: https://github.com/mrichardson23/mrBBIO

Okay, hello there! So, I'm quite in love with python. I started it about 4 months ago. I'm more than efficient in languages Java, VB.Net/C#, PHP, and some C/C++ and ASM. Python was a cinch to pick up.

I was wondering, in the likely event that I don't use the default BBB's OS, where can I get the python API files for this? From the original out-of-box OS and just copy the file over to the new /sys ?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.