Skip to content

Read all 4 buttons with one call. #11

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 3 commits into from
Jul 31, 2023
Merged
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
13 changes: 13 additions & 0 deletions adafruit_neokey/neokey1x4.py
Original file line number Diff line number Diff line change
@@ -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)