NodeMCU & KY-040 rotary encoder

NodeMCU & KY-040 rotary encoder

The KY-040 rotary encoder module is part of the 37 sensors set that I am hooking up to a NodeMCU. The rotary encoder works on the principle of 2 pins on a rotary blade where by detecting which connection is made first you know which the knob is turned. A very good explanation can be found here.

To connect the rotary switch you do the following. Connect GND to ground and + to 3.3v. Than connect SW to 3.3v with a 10k resistor and connect SW to a digital input (in my example 5). Connect DT to 3.3v with a 10k resistor and connect DT to a digital input (in my example 3). Connect CLK with a 10k resistor to 3.3v and connect CLK to a digital input (in my example 4). What the rotary encoder does is connect ground to pins DT and CLK in sequence and the sequence is determined by whether you rotate right or left.

I have made many attempts to create working code for the NodeMCU. Unfortunately, it seems a bit to slow to catch all the triggers. With every rotation you would expect ports 3 and 4 to send two triggers, 0 and 1 and by checking the value of the other pin you would know whether it is turning left or right.

The code that seems to work the best is this one:

function rotaryturn3 (level)
  if level~=gpio.read(4) then
    print("Turning right")
  end
end

function rotaryturn4 (level)
  if level~=gpio.read(3) then
    print("Turning left")
  end
end

function rotarybutton (level)
  if level==0 then
    print("Button pushed")
  else
    print("Button released")
  end
end

gpio.mode(3,gpio.INPUT)
gpio.mode(4,gpio.INPUT)

gpio.trig(3,"both",rotaryturn3)
gpio.trig(4,"both",rotaryturn4)

gpio.trig(5,"both",rotarybutton)

Unfortunately the code does not always give the right result, so you can get a left once in a while when you are turning the knob right or the other way around.

 

One thought on “NodeMCU & KY-040 rotary encoder

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s