adafruit / Adafruit_CircuitPython_CLUE

A high-level library representing all the features of the Adafruit CLUE
MIT License
31 stars 20 forks source link

Capacitive touch iterable attribute #41

Open kattni opened 3 years ago

kattni commented 3 years ago

This code was designed in response to this issue.

The following is written in the context of the Circuit Playground Express, but it appears touch was implemented in the CLUE library in the same way, so it should be applied here as well.

It is a start for another library that could be for the Circuit Playground Express, or usable across multiple boards. I'm posting the code here so anyone who wants to pick this up has a place to start. The idea is to allow for iteration across all capacitive touch inputs (in the current case, the touch pads on the CPX), and return strings, ints or pin instances for use. It could possibly be written into a class that uses touch state. Or it could be expandable to include all inputs that provide boolean values, such as buttons as well.

As it is, it initialises all of the touch pads as touch pads, which on the CPX means that none of those pads can be used anything else, such as digital outputs, at the same time that this function is called. This may not be an issue in the eventual library, but it's something to be aware of.

The functions are:

def touched_padname(self):
    pin = (board.A1, board.A2, board.A3, board.A4, board.A5, board.A6, board.A7)
    touch = tuple(touchio.TouchIn(p) for p in pin)
    return ['A{}'.format(i+1) for (i, v) in enumerate(touch) if v.value]

def touched(self):
    pin = (board.A1, board.A2, board.A3, board.A4, board.A5, board.A6, board.A7)
    touch = tuple(touchio.TouchIn(p) for p in pin)
    return [i for (i, v) in enumerate(touch) if v.value]

This allows for use like the following examples. It is by no means limited to the simplicity of these examples.

for pad in cpx.touched:
    print("pad {0} touched!".format(pad))
if 1 in cpx.touched:
    print("pad 1 touched!")
if 'A1' in cpx.touched:
    print("pad A1 touched!")
COMBO = ('A1', 'A2', 'A5')
if all(pad in cpx.touched for pad in COMBO):
    print("UNLOCKED!")

Opened here from original issue here.

tekktrik commented 2 years ago

@kattni let me know if you want me to port the code from the CPX PR to here as well