diff --git a/adafruit_neokey/neokey1x4.py b/adafruit_neokey/neokey1x4.py index 2405bcb..3251e8e 100644 --- a/adafruit_neokey/neokey1x4.py +++ b/adafruit_neokey/neokey1x4.py @@ -71,3 +71,16 @@ def __getitem__(self, index: int) -> bool: if not isinstance(index, int) or (index < 0) or (index > 3): raise RuntimeError("Index must be 0 thru 3") return not self.digital_read(index + 4) + + def get_keys(self) -> typing.List[bool]: + """Read all 4 keys at once and return an array of booleans. + + Returns: + typing.List[bool]: _description_ + """ + # use a bit mask with ports 4-7 to read all 4 keys at once + bulk_read = self.digital_read_bulk(0xF0) + + # convert the leftmost 4 bits to an array of booleans and return + keys = [bulk_read & (1 << i) == 0 for i in range(4, 8)] + return keys diff --git a/examples/neokey1x4_allkeys.py b/examples/neokey1x4_allkeys.py new file mode 100644 index 0000000..4dc1115 --- /dev/null +++ b/examples/neokey1x4_allkeys.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT +"""NeoKey simpletest.""" +from time import sleep +import board +from adafruit_neokey.neokey1x4 import NeoKey1x4 + +# use default I2C bus +i2c_bus = board.I2C() + +# Create a NeoKey object +neokey = NeoKey1x4(i2c_bus, addr=0x30) + +print("Adafruit NeoKey simple test reading all keys") + +# neokey.edbug = True + +while True: + keys = neokey.get_keys() + print(f"keys {keys}") + # test for all buttons pressed at once + if keys[0] and keys[1] and keys[2] and keys[3]: + for i in range(4): + neokey.pixels[i] = 0xFF00FF + # check each key individually + else: + if keys[0]: + print("Button A") + neokey.pixels[0] = 0xFF0000 + else: + neokey.pixels[0] = 0x0 + + if keys[1]: + print("Button B") + neokey.pixels[1] = 0xFFFF00 + else: + neokey.pixels[1] = 0x0 + + if keys[2]: + print("Button C") + neokey.pixels[2] = 0x00FF00 + else: + neokey.pixels[2] = 0x0 + + if keys[3]: + print("Button D") + neokey.pixels[3] = 0x00FFFF + else: + neokey.pixels[3] = 0x0 + + sleep(0.5)