Skip to content

Commit 46f9f8a

Browse files
authored
Merge pull request #11 from EAGrahamJr/all-the-buttons
Read all 4 buttons with one call.
2 parents 816c9cc + 8d5ecc9 commit 46f9f8a

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

adafruit_neokey/neokey1x4.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,16 @@ def __getitem__(self, index: int) -> bool:
7171
if not isinstance(index, int) or (index < 0) or (index > 3):
7272
raise RuntimeError("Index must be 0 thru 3")
7373
return not self.digital_read(index + 4)
74+
75+
def get_keys(self) -> typing.List[bool]:
76+
"""Read all 4 keys at once and return an array of booleans.
77+
78+
Returns:
79+
typing.List[bool]: _description_
80+
"""
81+
# use a bit mask with ports 4-7 to read all 4 keys at once
82+
bulk_read = self.digital_read_bulk(0xF0)
83+
84+
# convert the leftmost 4 bits to an array of booleans and return
85+
keys = [bulk_read & (1 << i) == 0 for i in range(4, 8)]
86+
return keys

examples/neokey1x4_allkeys.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
"""NeoKey simpletest."""
4+
from time import sleep
5+
import board
6+
from adafruit_neokey.neokey1x4 import NeoKey1x4
7+
8+
# use default I2C bus
9+
i2c_bus = board.I2C()
10+
11+
# Create a NeoKey object
12+
neokey = NeoKey1x4(i2c_bus, addr=0x30)
13+
14+
print("Adafruit NeoKey simple test reading all keys")
15+
16+
# neokey.edbug = True
17+
18+
while True:
19+
keys = neokey.get_keys()
20+
print(f"keys {keys}")
21+
# test for all buttons pressed at once
22+
if keys[0] and keys[1] and keys[2] and keys[3]:
23+
for i in range(4):
24+
neokey.pixels[i] = 0xFF00FF
25+
# check each key individually
26+
else:
27+
if keys[0]:
28+
print("Button A")
29+
neokey.pixels[0] = 0xFF0000
30+
else:
31+
neokey.pixels[0] = 0x0
32+
33+
if keys[1]:
34+
print("Button B")
35+
neokey.pixels[1] = 0xFFFF00
36+
else:
37+
neokey.pixels[1] = 0x0
38+
39+
if keys[2]:
40+
print("Button C")
41+
neokey.pixels[2] = 0x00FF00
42+
else:
43+
neokey.pixels[2] = 0x0
44+
45+
if keys[3]:
46+
print("Button D")
47+
neokey.pixels[3] = 0x00FFFF
48+
else:
49+
neokey.pixels[3] = 0x0
50+
51+
sleep(0.5)

0 commit comments

Comments
 (0)