Skip to content

Commit 07ffe38

Browse files
authored
Merge pull request #9 from caternuson/iss1
Add per channel property style access
2 parents 239134c + 7848c6e commit 07ffe38

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

adafruit_mpr121.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,45 @@
7979
MPR121_SOFTRESET = const(0x80)
8080
# pylint: enable=bad-whitespace
8181

82+
class MPR121_Channel():
83+
"""Helper class to represent a touch channel on the MPR121. Not meant to
84+
be used directly."""
85+
def __init__(self, mpr121, channel):
86+
self._mpr121 = mpr121
87+
self._channel = channel
88+
89+
@property
90+
def value(self):
91+
"""Whether the touch pad is being touched or not."""
92+
return self._mpr121.touched() & (1 << self._channel) != 0
93+
94+
@property
95+
def raw_value(self):
96+
"""The raw touch measurement."""
97+
return self._mpr121.filtered_data(self._channel)
8298

8399
class MPR121:
84100
"""Driver for the MPR121 capacitive touch breakout board."""
85101

86102
def __init__(self, i2c, address=MPR121_I2CADDR_DEFAULT):
87103
self._i2c = i2c_device.I2CDevice(i2c, address)
88104
self._buffer = bytearray(2)
105+
self._channels = [None]*12
89106
self.reset()
90107

108+
def __getitem__(self, key):
109+
if key < 0 or key > 11:
110+
raise IndexError('Pin must be a value 0-11.')
111+
if self._channels[key] is None:
112+
self._channels[key] = MPR121_Channel(self, key)
113+
return self._channels[key]
114+
115+
@property
116+
def touched_pins(self):
117+
"""A tuple of touched state for all pins."""
118+
touched = self.touched()
119+
return tuple([bool(touched >> i & 0x01) for i in range(12)])
120+
91121
def _write_register_byte(self, register, value):
92122
# Write a byte value to the specifier register address.
93123
with self._i2c:

examples/mpr121_simpletest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,6 @@
2222
for i in range(12):
2323
# Call is_touched and pass it then number of the input. If it's touched
2424
# it will return True, otherwise it will return False.
25-
if mpr121.is_touched(i):
25+
if mpr121[i].value:
2626
print('Input {} touched!'.format(i))
2727
time.sleep(0.25) # Small delay to keep from spamming output messages.

0 commit comments

Comments
 (0)