{"id":197,"date":"2020-05-25T15:12:09","date_gmt":"2020-05-25T15:12:09","guid":{"rendered":"https:\/\/samndave.org.uk\/ourdoc\/?p=197"},"modified":"2025-07-10T16:11:34","modified_gmt":"2025-07-10T16:11:34","slug":"microbit-rotary-encoder","status":"publish","type":"post","link":"https:\/\/samndave.org.uk\/index.php\/2020\/05\/25\/microbit-rotary-encoder\/","title":{"rendered":"Micro:bit Rotary Encoder"},"content":{"rendered":"\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"311\" height=\"266\" src=\"http:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/05\/rotary_encoder.jpg\" alt=\"\" class=\"wp-image-196\" srcset=\"https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/05\/rotary_encoder.jpg 311w, https:\/\/samndave.org.uk\/wp-content\/uploads\/2020\/05\/rotary_encoder-300x257.jpg 300w\" sizes=\"auto, (max-width: 311px) 100vw, 311px\" \/><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">A rotary encoder, such as the common KY-040 above, is a knob that you can turn continuously  either clockwise or anti-clockwise and detect which direction it is being turned. Types such as the KY-040 are known as incremental encoders. These will tell you the direction they are being turned, but can not report which direction they are pointing. The shaft can be pushed down to act like a push button. A common application for this is to navigate menu screens on devices such as 3d printers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To connect a KY-040 to a Micro:bit, + and GND go to 3V and GND on the Micro:bit. The other three pins go to any digital input pins. In the following examples, SW goes to pin0, DT to pin1 and CLK to pin2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a detailed explanation of how rotary encoders work, see <a href=\"https:\/\/en.wikipedia.org\/wiki\/Rotary_encoder#Incremental_encoder\">wikipedia<\/a>. To use one, all you need to know is if CLK changes, then the encoder is being turned. If CLK is the same as DT (could be high or low), then it is being turned anti-clockwise. If CLK is different to DT it is being turned clockwise. Generally the sensitivity is changed with a sleep statement. The button on the top acts as a simple push button. The CLK and DT  pins have their own internal resistors so we must disable the internal pull-up resistor to work. For a description about this, see <a href=\"https:\/\/samndave.org.uk\/2020\/05\/17\/microbit-buttons\/\">Micro:bit Buttons<\/a>. The one on the switch is still required.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This gives us a basic procedure to follow to read input from a rotary encoder:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Define the pins in use<\/li><li>Disable the internal pull-up resistors.<\/li><li>Read CLK and store this in a variable for the last known state of CLK.<\/li><li>Start a loop:<ul><li>Read all three input pins<\/li><li>If CLK has changed since the last known state of CLK (lastCLK), the encoder is moving.<ul><li>If CLK is not equal to DT it is moving clockwise<\/li><li>Otherwise it is moving anti-clockwise.<\/li><li>Wait, according to the sensitivity you want<\/li><li>Set lastCLK equal to CLK<\/li><\/ul><\/li><li>Check for button press<\/li><li>Return to start of loop<\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In code form, this makes:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Rotary encoder test\nfrom microbit import *\n\nRSW = pin0\nRDT = pin1\nRCLK = pin2\n\n# KY-040 has its own pull up resistors.\n# Disable the Micro:bit internal ones but\n# ensure we use the one for the switch pin\nRCLK.set_pull( RCLK.NO_PULL )\nRDT.set_pull ( RDT.NO_PULL )\nRSW.set_pull ( RSW.PULL_UP )\n\nclkLast = RCLK.read_digital()\n\nprint ( \"Ready to start\" )\ndisplay.show ( Image.HAPPY )\n\nwhile True:\n    clk = RCLK.read_digital()\n    dt = RDT.read_digital()\n    sw = RSW.read_digital()\n\n    if ( clk != clkLast ) :\n        if ( clk != dt ) :\n            print ( \"Clockwise\" )\n            display.show(Image.ARROW_E)\n            sleep(300)\n        else:\n            print ( \"Anti-clockwise\" )\n            display.show(Image.ARROW_W)\n            sleep(300)\n\n        clkLast = clk\n    else:\n        # Has the switch been pressed?\n        if (sw == 0) :\n            display.show('X')\n            sleep(500)\n        else :\n            display.clear()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There is a problem with this approach. If you try it and watch either the arrows or serial lines, you find while turning the encoder, you occasionally get the wrong direction reported. This is known as &#8216;switch bounce&#8217; and is often caused by cheaper components in encoders such as the KY-040. There are many ways to look at solving this, either in hardware using capacitors or in code. In a few tests with capacitors, I did not find a significant difference. However I always found that the wrong direction was reported once in a row, never twice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A &#8216;quick and dirty&#8217; solution is to wrap up the detection into a function which takes a number of readings then reports back which direction was detected the most. This does mean it will take a little longer to react to a turn or change in direction, but only by a fraction of a second. In the code below, the function readEncoder returns a pair of values for the direction and the state of the switch. A 0 represents no movement, 1 for clockwise movement and -1 for anti-clockwise.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In python, you can build lists of values in brackets with a comma, e.g. a=(2, 4, 8). To access the first element of the list, use square brackets, a[0]. For the third value, a[2]. This allows us to return the direction as the first value and the switch state as the second. The function in the below code takes a few attempts to read the encoder direction and returns a pair of values, the first for the direction and the second for the switch state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Rotary encoder test\nfrom microbit import *\n\nRSW = pin0\nRDT = pin1\nRCLK = pin2\n\n# KY-040 has its own pull up resistors.\n# Disable the Micro:bit internal ones but\n# ensure we use the one for the switch pin\nRCLK.set_pull(RCLK.NO_PULL)\nRDT.set_pull(RDT.NO_PULL)\nRSW.set_pull(RSW.PULL_UP)\n\ndef readEncoder():\n    # Return a pair of values direction and switch state\n    #   0 = no movement\n    #   1 = clockwise\n    #   2 = anti-clockwise\n    \n    # Set sensitivity - how long we wait between readings in ms\n    sens = 50\n    # Accuracy is how many checks we perform. This should at least\n    # be 3. Note that the more checks, the longer it will take and\n    # the greater the chance of the direction changing while we checks\n    acc = 5\n    \n    # Record the last known state of the CLK line\n    clkLast = RCLK.read_digital()\n    \n    # Set direction counters, clockwise and anti-clockwise\n    cw = 0\n    ac = 0\n    \n    # Checking loop\n    for i in range(0, acc):\n        # Read data from the encoder\n        clk = RCLK.read_digital()\n        dt = RDT.read_digital()\n        sw = RSW.read_digital()\n        \n        if(clk != clkLast):\n            # print (\"clkLast = \"+str(clkLast)+\" - clk = \"+str(clk)+\" - dt = \"+str(dt))\n            if(clkLast != dt):\n                # Clockwise, add 1 to clockwise count\n                cw = cw+1\n            else:\n                # Anti-clockwise, add 1 to anti-clockwise count\n                ac = ac+1\n\n            # Record the last known state of the clock\n            clkLast = clk\n            # Wait according to sensitivity setting\n            sleep(sens)\n            \n    # Initially assume the direction is 0\n    d = 0\n    # Check the clockwise and anti-clockwise counters\n    # If they are the same, no change to d is made. We assume\n    # the encoder is not moving\n    if(cw > ac):\n        # More clockwise movement than anti-clockwise\n        d = 1\n    elif(ac > cw):\n        # More anti-clockwise movement than clockwise\n        d = -1\n\n    # Return data as a pair\n    # We can return the value of the switch directly\n    return (d, sw)\n# End of readEncoder\n\nprint(\"Ready to start\")\ndisplay.show(Image.HAPPY)\nsleep(1000)\n\n# Main loop\nwhile True:\n    r = readEncoder()\n    \n    # Check the direction and report. The screen\n    # will show the last recorded direction\n    if(r&#91;0] == 1):\n        # Clockwise movement\n        print(\"Clockwise\")\n        display.show(Image.ARROW_E)\n    elif(r&#91;0] == -1):\n        # Anti-clockwise movement\n        print(\"Anti-clockwise\")\n        display.show(Image.ARROW_W)\n     \n    # Check for a switch press\n    if(r&#91;1] == 0):\n        display.show('X')\n        sleep(500)\n        display.clear()<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>A rotary encoder, such as the common KY-040 above, is a knob that you can [&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-197","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\/197","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=197"}],"version-history":[{"count":1,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/197\/revisions"}],"predecessor-version":[{"id":1178,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/posts\/197\/revisions\/1178"}],"wp:attachment":[{"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/media?parent=197"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/categories?post=197"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/samndave.org.uk\/index.php\/wp-json\/wp\/v2\/tags?post=197"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}