Skip to content

Commit 0835d20

Browse files
committed
Merge pull request #1 from dsmall/master
This adds pinMode() and readPins(), which are used in the test-pins.html demo, and are generally useful.
2 parents b3b0472 + 35a71de commit 0835d20

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

pytronics.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
# text of the GNU General Public License at
1515
# <http://www.gnu.org/licenses/gpl.txt> for the details.
1616

17+
# Listing of /sys/class/gpio
18+
# export gpio107 gpio66 gpio69 gpio72 gpio97 gpiochip32 unexport
19+
# gpio100 gpio64 gpio67 gpio70 gpio73 gpio98 gpiochip64
20+
1721
def decode_pin_name(pin):
1822
names = {
1923
'LED': 107, # PC11
@@ -53,12 +57,16 @@ def analogRead(pin):
5357
def analogWrite():
5458
pass
5559

60+
# Reads a value from a specified digital pin
61+
# Returns '0' or '1'
5662
def digitalRead(pin):
5763
pin = decode_pin_name(pin)
5864
with open('/sys/class/gpio/gpio' + str(pin) + '/value', 'r') as f:
5965
reading = f.read()
6066
return reading.strip()
6167

68+
# Write a HIGH or LOW value to a digital pin
69+
# E.g. digitalWrite('11', 'HIGH')
6270
def digitalWrite(pin, state):
6371
pin = decode_pin_name(pin)
6472
with open('/sys/class/gpio/gpio' + str(pin) + '/value', 'w') as f:
@@ -67,6 +75,32 @@ def digitalWrite(pin, state):
6775
else:
6876
f.write('0')
6977

78+
# Configures the specified pin to behave either as an input or an output
79+
# E.g. pinMode('5', 'INPUT')
80+
def pinMode(pin, mode):
81+
pin = decode_pin_name(pin)
82+
with open('/sys/class/gpio/gpio' + str(pin) + '/direction', 'w') as f:
83+
if (mode == 'INPUT'):
84+
f.write('in')
85+
else:
86+
f.write('out')
87+
88+
# Called with list of pins e.g. [ 'LED' ]
89+
# Returns dictionary of tuples { 'pin': (direction, value) }
90+
def readPins(pinlist):
91+
pins = {}
92+
for pin in pinlist:
93+
syspin = str(decode_pin_name(pin))
94+
try:
95+
with open('/sys/class/gpio/gpio' + syspin + '/direction', 'r') as f:
96+
direction = f.read().strip()
97+
with open('/sys/class/gpio/gpio' + syspin + '/value', 'r') as f:
98+
value = f.read()
99+
pins[pin] = (direction.strip(), value.strip())
100+
except:
101+
print ('## readPins ## Cannot access pin {0} ({1})'.format(pin, syspin))
102+
return pins
103+
70104
def i2cRead():
71105
pass
72106

0 commit comments

Comments
 (0)