Home Micro BitMicro Bit Code Microbit and an AD keypad

Microbit and an AD keypad

I purchased this module as part of a microcontroller kit, its an interesting little module as it has 16 buttons but with only 1 I/O line is required, an analog input. You connect this to your Microbit and read in the value.

The concept is straightforward  you use a resistor network as voltage dividers, and then let each button feed a different voltage to the analog pin. So by detecting the voltage you can tell which button has been pressed. You can only detect one button at a time. This means rather than muliple I/O pins being required you can use 1, it does mean you need to detect the analogue value of the button pressed and act on in your code but this is not that a difficult task

A_D-Keypad-2

 

Here is the schematic of the module, hopefully you can see what I described earlier

AD-Keypad-Schematic-1024x723

 

Code

 

[codesyntax lang=”python”]

from microbit import *

while True:
    reading = pin0.read_analog()
    sleep(100)
    if reading < 990:
        print("Reading: " + str(reading))
        sleep(250)

[/codesyntax]

Testing

Open up the REPL window and press the keys individually, take a note of the values displayed. Here is what I saw

Reading: 2
Reading: 67
Reading: 132
Reading: 198
Reading: 261
Reading: 323
Reading: 387
Reading: 452
Reading: 513
Reading: 577
Reading: 641
Reading: 698
Reading: 759
Reading: 822
Reading: 884
Reading: 945

You can then use these values, if you take a look at them you will see a range. Take key 2 which returned 67, you don’t want to look for exactly 67 but between a range of numbers. The difference between the values returned is around 60 so a good starting point would be 30 lower and 30 higher, so to detect key 2 being pressed you would do the following

if reading > 40 and reading < 94:
Do Something

 

[codesyntax lang=”python”]

from microbit import *

while True:
    reading = pin0.read_analog()  
    sleep(100)
    if reading > 1 and reading < 39:
        num = 1
    elif reading > 40 and reading < 94:
        num = 2
    elif reading > 95 and reading < 164:
        num = 3
    elif reading > 165 and reading < 218:
        num = 4
    elif reading > 219 and reading < 290:
        num = 5
    elif reading > 291 and reading < 354:
        num = 6
    elif reading > 355 and reading < 418:
        num = 7
    elif reading > 419 and reading < 485:
        num = 8
    elif reading > 486 and reading < 544:
        num = 9
    else:
        num = 0
    print("Number: " + str(num))

[/codesyntax]

You may also like