Looking for Spin example to look up a value in a list — Parallax Forums

# Looking for Spin example to look up a value in a list

Posts: 1,632

I've been messing around with Beau Schwabe's 4x4 keypad demo. It produces a word and depending on which key is pressed sets a bit in the word. The keypad I have has these keys in the order in which I see the bits set (*, 0, #, D, 7, 8, 9, C, 4, 5, 6, B, 1, 2, 3, A). For instance 0100000000000000 would be the "0" key pressed.
How do I iterate through the list to get the corresponding character that aligns with the bit set in the word?

• Posts: 1,632
edited 2021-04-17 16:56

I got this to work:

```VAR

PUB start | idx
' Start PST
text.start(115200)

repeat
repeat idx from 0 to 15
if (keypad >> idx) == 1
text.position(5, 2)
text.str(@keys[idx])

DAT

keys  word  "A", "3", "2", "1", "B", "6", "5", "4", "C", "9", "8", "7", "D", "#", "0", "*"
```

Is there any better or simpler way?

• Posts: 1,632

BTW how do you post code in the forum. I tried [/code] and [\code]...

• Posts: 1,642

Triple backticks, like this:.

```
Code goes here
```

• Posts: 1,632

Thanks. I changed it.

• Posts: 2,056
edited 2021-04-17 21:41

You can also use a CASE statement.
Not necessarily better, just easier to read.

And then list all possible states for the keypad

```  repeat
text.str(string(\$A,5,\$B,2))
text.str(string(\$A,5,\$B,3))
text.str(string(\$A,5,\$B,4))
text.str(string(\$A,5,\$B,5))
text.str(string(\$A,5,\$B,9))

%0100000000000000:     'Zero key pressed.
Do something

%0000000000000000:     'No key pressed
Do something
```

You can find the correct binary number when you see what the RAW keypad value is on your terminal output.
You can then place that entire binary number into the CASE statement like I did for two of the binary positions.

• Posts: 7,568
edited 2021-04-17 21:35

How do I iterate through the list to get the corresponding character that aligns with the bit set in the word?

No need to iterate. The >| (encode) operator will tell you which bit is set (+1). This routine will turn your bit into an ASCII character.

```dat

KeyChar       byte    "*0#D789C456B123A"

pub translate_key(keybits)

if (keybits)
return KeyChar[>|keybits - 1]
```

This will return 0 if no key was pressed, or the ASCII char if one was.

• Posts: 2,468

Or:

```    keypad := KP.ReadKeyPad
keychar := lookup( >|keypad : "*0#D789C456B123A")
```
• Posts: 1,632

Thanks for the help. Much appreciated.