Skip to content

Commit

Permalink
Merge pull request #11 from EAGrahamJr/all-the-buttons
Browse files Browse the repository at this point in the history
Read all 4 buttons with one call.
  • Loading branch information
FoamyGuy committed Jul 31, 2023
2 parents 816c9cc + 8d5ecc9 commit 46f9f8a
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
13 changes: 13 additions & 0 deletions adafruit_neokey/neokey1x4.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
51 changes: 51 additions & 0 deletions examples/neokey1x4_allkeys.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 46f9f8a

Please sign in to comment.