Skip to content

Add per channel property style access #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions adafruit_mpr121.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,45 @@
MPR121_SOFTRESET = const(0x80)
# pylint: enable=bad-whitespace

class MPR121_Channel():
"""Helper class to represent a touch channel on the MPR121. Not meant to
be used directly."""
def __init__(self, mpr121, channel):
self._mpr121 = mpr121
self._channel = channel

@property
def value(self):
"""Whether the touch pad is being touched or not."""
return self._mpr121.touched() & (1 << self._channel) != 0

@property
def raw_value(self):
"""The raw touch measurement."""
return self._mpr121.filtered_data(self._channel)

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

def __init__(self, i2c, address=MPR121_I2CADDR_DEFAULT):
self._i2c = i2c_device.I2CDevice(i2c, address)
self._buffer = bytearray(2)
self._channels = [None]*12
self.reset()

def __getitem__(self, key):
if key < 0 or key > 11:
raise IndexError('Pin must be a value 0-11.')
if self._channels[key] is None:
self._channels[key] = MPR121_Channel(self, key)
return self._channels[key]

@property
def touched_pins(self):
"""A tuple of touched state for all pins."""
touched = self.touched()
return tuple([bool(touched >> i & 0x01) for i in range(12)])

def _write_register_byte(self, register, value):
# Write a byte value to the specifier register address.
with self._i2c:
Expand Down
2 changes: 1 addition & 1 deletion examples/mpr121_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
for i in range(12):
# Call is_touched and pass it then number of the input. If it's touched
# it will return True, otherwise it will return False.
if mpr121.is_touched(i):
if mpr121[i].value:
print('Input {} touched!'.format(i))
time.sleep(0.25) # Small delay to keep from spamming output messages.