{"id":237,"date":"2020-08-03T14:57:18","date_gmt":"2020-08-03T14:57:18","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=237"},"modified":"2025-07-10T16:11:34","modified_gmt":"2025-07-10T16:11:34","slug":"microbit-keypads","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2020\/08\/03\/microbit-keypads\/","title":{"rendered":"Micro:bit Keypads"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"609\" height=\"546\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/08\/keypads.jpg\" alt=\"\" class=\"wp-image-238\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/08\/keypads.jpg 609w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/08\/keypads-300x269.jpg 300w\" sizes=\"auto, (max-width: 609px) 100vw, 609px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Keypads make a convenient way to add lots of buttons to a Micro:bit and they come in a range of sizes. The type above are known as membrane keypads. They have a sticky back, are lightly waterproof and can be wiped clean.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4 x 1 Keypad<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A 4 x 1 keypad is named as it is 4 buttons in 1 row. It comes with a ribbon connector cable, with 5 pins. There is one pin for each key and one for ground. The wiring for these can always differ, so it is worth checking. Often ground is on a strip of cable on it&#8217;s own. The connector usually had a small number on each end denoting the pin number. On the keypad pictured above, the pinout, going from left to right is:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table><tbody><tr><td><strong>Pin<\/strong><\/td><td><strong>Function<\/strong><\/td><td><strong>Micro:bit<\/strong><\/td><\/tr><tr><td>1<\/td><td>Ground<\/td><td>Gnd<\/td><\/tr><tr><td>2<\/td><td>Key &#8216;2&#8217;<\/td><td>pin0<\/td><\/tr><tr><td>3<\/td><td>Key &#8216;1&#8217;<\/td><td>pin1<\/td><\/tr><tr><td>4<\/td><td>Key &#8216;4&#8217;<\/td><td>pin2<\/td><\/tr><tr><td>5<\/td><td>Key &#8216;3&#8217;<\/td><td>pin8<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">You can see from the above the wiring does not go 1, 2, 3, 4 as you may expect. Sometimes these keypads can have different symbols or be blank.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Have a quick read up on <a href=\"Micro:bit buttons\">Micro:bit buttons<\/a> to see how a basic push button works on a Micro:bit. If we use a variable for each button and assign it to a pin we can set an internal pull up resistor then use read_digital() to get the state. The following code will show on the display which button is being pressed:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># 4x1 keypad\n\nfrom microbit import *\n\n# Define our wiring. The 5th connection goes to ground\nkey1 = pin1\nkey2 = pin0\nkey3 = pin8\nkey4 = pin2\n\n# Set internal pullup resistor\nkey1.set_pull(key1.PULL_UP)\nkey2.set_pull(key2.PULL_UP)\nkey3.set_pull(key3.PULL_UP)\nkey4.set_pull(key4.PULL_UP)\n\nwhile True:\n    if ( key1.read_digital() == 0 ):\n        display.show(\"1\")\n        sleep(500)\n        display.clear()\n    if ( key2.read_digital() == 0 ):\n        display.show(\"2\")\n        sleep(500)\n        display.clear()\n    if ( key3.read_digital() == 0 ):\n        display.show(\"3\")\n        sleep(500)\n        display.clear()\n    if ( key4.read_digital() == 0 ):\n        display.show(\"4\")\n        sleep(500)\n        display.clear()        <\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There is a lot of repeated code there and the program does not scale well if we were to use a different sized keypad. We can take advantage of arrays in Python to avoid writing the same code over and over again. Read up on arrays at <a href=\"https:\/\/www.w3schools.com\/python\/python_arrays.asp\">w3schools<\/a>. Rather than use a straightforward array of single values, we use a two dimensional array. Each value in the array keypad is a small array itself, with two elements, the pin number and the value. Lists start at 0, so we can access the value of the second pin with <code>keypad[1][1]<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># 4x1 keypad\n\nfrom microbit import *\n\n# Create our pinout as a list. Use pairs of values\n# of &#91; pin, value ]\nkeypad = &#91; &#91;pin1, \"1\"],\n           &#91;pin0, \"2\"],\n           &#91;pin8, \"3\"],\n           &#91;pin2, \"4\"] ]\n\n\n# Set internal pullup resistor, looping through the list\nfor k in keypad:\n    k&#91;0].set_pull(k&#91;0].PULL_UP)\n\nwhile True:\n    # Loop through list checking for keypress\n    for k in keypad:\n        if ( k&#91;0].read_digital() == 0 ):\n            display.show(k&#91;1])\n            sleep(500)\n            display.clear()\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4&#215;4 Keypads<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We learned above that smaller keypads have one pin for each button, plus an additional pin for ground. A 2 button keypad will have 3 pins, a 4 button keypad has 5 pins. A 4&#215;4 keypad has 16 keys, so it should have 17 pins, right? No, it only has 8 pins, so what is going on here?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The image below shows a circuit diagram of a 4&#215;4 keypad:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"648\" height=\"389\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/08\/4x4keypad.png\" alt=\"\" class=\"wp-image-240\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/08\/4x4keypad.png 648w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/08\/4x4keypad-300x180.png 300w\" sizes=\"auto, (max-width: 648px) 100vw, 648px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The wiring forms a matrix. If you trace the circuit through, you can see if the &#8216;5&#8217; key is pressed, a connection is formed between pin 7 and pin 3. If we can detect these connections then we can work out what button is being pressed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Rather than use 8 IO pins on the Micro:bit, we can use a PCF8574 module to easily plug in the keypad and use some binary or hex to quickly work out what buttons are being pressed. Read up on the PCF8574, binary and hex <a rel=\"noreferrer noopener\" href=\"https:\/\/samndave.org.uk\/2020\/08\/01\/microbit-more-io-pins-pcf8574-binary-and-hex\/\" target=\"_blank\">here<\/a>. Connect the keypad to the PCF8574 board making sure pin 1 on the keypad goes to p0 on the board. P0 is labelled on the underside.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The PCF8574 has four connections, connect Vcc to 3v and GND to GND. The remaining two connections are for the I2C bus. SDA goes to pin 20 and SCL goes to pin 19. It does not matter if you already have a device plugged into these two pins on the Micro:bit. As I2C is a bus technology, it can support multiple devices, each with it&#8217;s own address. The three small switches on the PCF8574 are used to change the address of the board, leave then all as &#8216;Off&#8217;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On the PCF8574, if a pin set to be high is connected to a pin set to be low, then the high pin will be dragged low. If we set all the pins to high, except one row (for example pin 5), we can detect a button press on that row by a pin 1 to 4 also going low. We can write one value to set the pins then read it back, if there are no key presses on that row the value will be the same. If the value is different then something is being pressed. Cycle through pins 5 to 8 in turn setting each to be low then inspect to see if something is pressed and return what.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can follow the circuit diagram and make a table of what the two low values should be for each key press. As this forms an 8 bit binary string, we can also shorten each of these to give a unique hex value for each pin.<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table><tbody><tr><td><strong>Key<\/strong><\/td><td><strong>P8<\/strong><\/td><td><strong>P7<\/strong><\/td><td><strong>P6<\/strong><\/td><td><strong>P5<\/strong><\/td><td><strong>P4<\/strong><\/td><td><strong>P3<\/strong><\/td><td><strong>P2<\/strong><\/td><td><strong>P1<\/strong><\/td><td>Hex<\/td><\/tr><tr><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0x77<\/td><\/tr><tr><td>2<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0x7B<\/td><\/tr><tr><td>3<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>0x7D<\/td><\/tr><tr><td>4<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0xB7<\/td><\/tr><tr><td>5<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0xBB<\/td><\/tr><tr><td>6<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>0xBD<\/td><\/tr><tr><td>7<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0xD7<\/td><\/tr><tr><td>8<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0xDB<\/td><\/tr><tr><td>9<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>0xDD<\/td><\/tr><tr><td>A<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>0x7E<\/td><\/tr><tr><td>B<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>0xBE<\/td><\/tr><tr><td>C<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>0xDE<\/td><\/tr><tr><td>D<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>0xEE<\/td><\/tr><tr><td>*<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0xE7<\/td><\/tr><tr><td>0<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0xEB<\/td><\/tr><tr><td>#<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>1<\/td><td>0<\/td><td>1<\/td><td>0xED<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Similar to an array in Python, we can also use a data structure called a dictionary to store these hex values. An array uses an index number 0, 1, 2&#8230; etc for each entry, where as a dictionary can use anything else, even text. Read up <a href=\"https:\/\/www.w3schools.com\/python\/python_dictionaries.asp\">here<\/a>. If we make a dictionary with each of the above hex values as keys and the key symbol as the value, e.g. <code>keys[0xBB] = \"5\"<\/code>, we can quickly look up what key is pressed from the value returned from the PCF8574 board.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This gives us a process we can follow to detect key presses:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Create a variable with all the bits high except pin 5.<\/li><li>Send variable to the PCF8574 to set the pins.<\/li><li>Read data back from the PCF8574 and store in a variable.<\/li><li>If the value sent is different to the value received, a key on that row is being pressed<ul><li>Lookup that value in the dictionary and return the key press<\/li><\/ul><\/li><li>Skip to the next row and repeat if no press detected<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This is done in the readKeypad function in the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># 4x4 keypad\nfrom microbit import *\n\nPCF_ADDR = 0x20     # Use the base address of the PCF8574\n\n# I2C send, function to simplify writing\ndef sendI2C(addr, value):\n    # Convert sent value to a byte array, which is\n    # required for I2C\n    buf = bytearray(1)\n    buf&#91;0] = value\n    # Send value\n    i2c.write(addr, buf)\n    # Short delay to send\n    sleep(5)\n\ndef readI2C(addr):\n    # Read in as a single byte and return\n    v = i2c.read(addr, 1)&#91;0]\n    return v\n    \ndef readKeypad():\n    # Define array of keypress values\n    # Curly brackets are a dictionary as we are not\n    # using consecutive index values\n    keys = {}\n    keys&#91;0x77] = \"1\"\n    keys&#91;0x7B] = \"2\"\n    keys&#91;0x7D] = \"3\"\n    keys&#91;0xB7] = \"4\"\n    keys&#91;0xBB] = \"5\"\n    keys&#91;0xBD] = \"6\"\n    keys&#91;0xD7] = \"7\"\n    keys&#91;0xDB] = \"8\"\n    keys&#91;0xDD] = \"9\"\n    keys&#91;0x7E] = \"A\"\n    keys&#91;0xBE] = \"B\"\n    keys&#91;0xDE] = \"C\"\n    keys&#91;0xEE] = \"D\"\n    keys&#91;0xE7] = \"*\"\n    keys&#91;0xEB] = \"0\"\n    keys&#91;0xED] = \"#\"\n    \n    # Set the default keypress to be an empty string\n    # to mean nothing pressed\n    kp = \"\"\n    \n    # Start with a zero on bit 5, all the rest 1\n    setState = 0xEF\n    \n    for x in range(4):\n        sendI2C(PCF_ADDR, setState)\n        # Read value back\n        r = readI2C(PCF_ADDR)\n        \n        # If the return state is different to the set state, a\n        # key press has pulled one of the pins, 1-4 low\n        if(setState != r):\n            # print(\"setState=\",hex(setState),\", r=\",hex(r))\n            kp = keys&#91;r]\n            # Return key press\n            return kp\n            \n        # Move the zero up to the next pin with a left shift.\n        # We want to keep the value at 8 bits, so need to AND\n        # with FF. Also, a zero will be moved in from the right.\n        # OR with 0x01 to set this lower bit.\n        # e.g. 1110 1111 &lt;&lt; 1\n        #   = 11101 1110 &amp; 0xFF\n        #   =  1101 1110 | 0x01\n        #   =  1101 1111\n        setState = ( ( setState &lt;&lt; 1) &amp; 0xFF) | 0x01\n    \n    # Return keypress value\n    return kp\n\nwhile True:\n        # Read from keypad\n        kp = readKeypad()\n        # Clear if an empty string comes back\n        if( kp == \"\" ):\n            display.clear()\n        else:\n            # Otherwise show\n            display.show(kp)\n        sleep(200)\n   <\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Using a dictionary this way also allows you to change the meaning of keys. For example if you were making a calculator you could change the dictionary to return &#8216;+&#8217; instead of &#8216;A&#8217;. Remember you can use the bin() and hex() functions with print if you want to see what is going on for any stage of the above.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Keypads make a convenient way to add lots of buttons to a Micro:bit and they [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[],"class_list":["post-237","post","type-post","status-publish","format-standard","hentry","category-microbit","category-hardware"],"_links":{"self":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/237","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/comments?post=237"}],"version-history":[{"count":1,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/237\/revisions"}],"predecessor-version":[{"id":1174,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/237\/revisions\/1174"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=237"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=237"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=237"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}