2018-09-16 09:15:16 +02:00
|
|
|
import machine
|
|
|
|
|
|
|
|
from kmk.common.abstract.matrix_scanner import AbstractMatrixScanner
|
|
|
|
from kmk.common.consts import DiodeOrientation
|
2018-09-23 06:49:58 +02:00
|
|
|
from kmk.common.event_defs import matrix_changed
|
2018-09-16 09:15:16 +02:00
|
|
|
|
|
|
|
|
|
|
|
class MatrixScanner(AbstractMatrixScanner):
|
2018-09-22 02:22:03 +02:00
|
|
|
def __init__(self, cols, rows, active_layers, diode_orientation=DiodeOrientation.COLUMNS):
|
2018-09-16 09:15:16 +02:00
|
|
|
# A pin cannot be both a row and column, detect this by combining the
|
|
|
|
# two tuples into a set and validating that the length did not drop
|
2018-09-17 05:50:05 +02:00
|
|
|
#
|
|
|
|
# repr() hackery is because MicroPython Pin objects are not hashable.
|
|
|
|
# Technically we support passing either a string (hashable) or the
|
|
|
|
# Pin object directly here, so the hackaround is necessary.
|
|
|
|
unique_pins = {repr(c) for c in cols} | {repr(r) for r in rows}
|
2018-09-16 09:15:16 +02:00
|
|
|
if len(unique_pins) != len(cols) + len(rows):
|
|
|
|
raise ValueError('Cannot use a pin as both a column and row')
|
|
|
|
|
|
|
|
self.cols = [machine.Pin(pin) for pin in cols]
|
|
|
|
self.rows = [machine.Pin(pin) for pin in rows]
|
|
|
|
self.diode_orientation = diode_orientation
|
2018-09-22 02:22:03 +02:00
|
|
|
self.active_layers = active_layers
|
2018-10-01 09:31:45 +02:00
|
|
|
self.last_pressed_len = 0
|
2018-09-16 09:15:16 +02:00
|
|
|
|
|
|
|
if self.diode_orientation == DiodeOrientation.COLUMNS:
|
|
|
|
self.outputs = self.cols
|
|
|
|
self.inputs = self.rows
|
|
|
|
elif self.diode_orientation == DiodeOrientation.ROWS:
|
|
|
|
self.outputs = self.rows
|
|
|
|
self.inputs = self.cols
|
|
|
|
else:
|
|
|
|
raise ValueError('Invalid DiodeOrientation: {}'.format(
|
|
|
|
self.diode_orientation,
|
|
|
|
))
|
|
|
|
|
|
|
|
for pin in self.outputs:
|
|
|
|
pin.init(machine.Pin.OUT)
|
|
|
|
pin.off()
|
|
|
|
|
|
|
|
for pin in self.inputs:
|
|
|
|
pin.init(machine.Pin.IN, machine.Pin.PULL_DOWN)
|
|
|
|
pin.off()
|
|
|
|
|
2018-10-01 09:31:45 +02:00
|
|
|
def scan_for_pressed(self):
|
|
|
|
pressed = []
|
2018-09-16 09:15:16 +02:00
|
|
|
|
2018-10-01 09:31:45 +02:00
|
|
|
for oidx, opin in enumerate(self.outputs):
|
2018-09-16 09:15:16 +02:00
|
|
|
opin.value(1)
|
|
|
|
|
2018-10-01 09:31:45 +02:00
|
|
|
for iidx, ipin in enumerate(self.inputs):
|
|
|
|
if ipin.value():
|
|
|
|
pressed.append(
|
|
|
|
(oidx, iidx) if self.diode_orientation == DiodeOrientation.ROWS else (iidx, oidx) # noqa
|
|
|
|
)
|
2018-09-23 06:49:58 +02:00
|
|
|
|
2018-10-01 09:31:45 +02:00
|
|
|
opin.value(0)
|
2018-09-23 06:49:58 +02:00
|
|
|
|
2018-10-01 09:31:45 +02:00
|
|
|
if len(pressed) != self.last_pressed_len:
|
|
|
|
self.last_pressed_len = len(pressed)
|
|
|
|
return matrix_changed(pressed)
|
2018-09-23 06:49:58 +02:00
|
|
|
|
|
|
|
return None # The default, but for explicitness
|