Rotary Encoder with micro:bit
Today, we will learn about another electro-mechanical switch, the rotary encoder. It is a unique component as its output signal can be used to determine the direction that its knob is being rotated. Not only that, but it is capable of continuous rotation, unlike a regular potentiometer.
In this guide, we will connect it to a micro:bit and program it using the MakeCode editor.
After completing this guide, you will understand the basics in using a rotary encoder. This can be used to create many useful projects, such as a volume controller for your music or even a MIDI device to make your own music!
|Parts Used in This Guide|
Step 1 The Module
Let's take a closer look at the rotary encoder module.
It has five pins:
- Encoder Pin 1 (CLK)
- Encoder Pin 2(DT)
- Switch (SW)
- Power (+)
- Ground (GND)
Note: Please use the M-F jumper wires included in the kit to connect this module to the breadboard.
Step 2 Connect GND to GND
Step 3 Connect 3.3V to +
Step 4 Connect P0 to SW
Step 5 Connect P1 to DT
Step 6 Connect P2 to CLK
Step 7 Download the KY-040 package
First, open up MakeCode editor and start a new project.
We will need to download the KY-040 package for the rotary encoder module to work.
- Click on the 'Advanced' tab
- Click on 'Extensions' tab
- Type 'KY-040' in the search bar
- Click on 'rotary-encoder-KY-040' library and it will be added to the MakeCode editor
Step 8 Turn it left or right!
- From 'RotaryEncoder' tab, drag and drop a 'connect clk ... dt ... sw ..." block into the editor
- Change the values:
- CLK pin to Pin 2
- dt pin to Pin 1
- SW pin to Pin 0
- Grab a 'on rotated' block from 'RotaryEncoder' tab.
- Duplicate the 'on rotated' block by right-clicking it and selecting 'Duplicate'
- change its value from 'Left' to 'Right'
- From 'Basic' tab, get out a 'show string' block
- We want to show the string "<" when the rotary encoder is turned to the left, and show the string ">" when it is turned to the right.
Step 9 Show numbers!
- Remove the 'show string' blocks and replace them with 'change item by ...' blocks.
- Rename the variable 'Num'
- Let's do some calculations!
- Minus 5 from the variable, 'Num,' each time the rotary encoder is rotated left
- Add 5 to the variable, 'Num' each time the rotary encoder is rotated right
- Grab a 'forever' block in the Basic tab, and place a 'show number' block in it.
- Change its value to show the variable, 'Num'.
Step 10 Upload the code
- Connect the micro:bit to your computer using a microUSB cable
- Click on the 'Download' button in MakeCode editor
- Open up Finder on the Mac OSX or if you are using Windows, open up Windows explorer. Find the downloaded hex file in your Downloads folder.
- Drag and drop this hex file to the MICRO:BIT drive
- The micro:bit will flash as the code is being uploaded.
Now, if you turn the rotary encoder knob, the number will change and display on the micro:bit's LED matrix!