Rotary encoder KY-040

All that relates to the H/W
Post Reply
User avatar
Fernando Perez
Posts: 378
Joined: Mon Feb 15, 2021 10:09 pm
Location: Santander (Spain)
Has thanked: 195 times
Been thanked: 266 times

Rotary encoder KY-040

Post by Fernando Perez »

I have bought a batch of KY-040 rotary encoders, the most economical, at a good price at:
https://www.amazon.es/dp/B07SV5HHM5?ref ... tails&th=1
As always, the result is disastrous. But it seems that this time I have achieved, based on the
https://github.com/enjoyneering/RotaryEncoder library, an acceptable, fluid and jump-free operation.

Code: [Local Link Removed for Guests]

' rotary encoder KY-040
' It does not use either the resistors on the board or the connection to Vcc.
' ESSENTIAL two 100nF capacitors between CLK/DT and GND

CL = 14 ' clk pin to D5 Wemos D1 mini
DT = 12 ' dt  pin to D6 Wemos D1 mini 

counter = 0 : position = 0
minPos = 0  : maxPos = 50

pin.mode CL, input, pullup  ' enable internal pull-up resistors 
pin.mode DT, input, pullup
interrupt CL, readCL

goto bucle
wait
END

bucle:
  while 1
    if position <> counter then
      wlog counter
      position = counter
    endif
  wend
return
  
' ---------------------------
readCL:
  if pin(CL) = 0 then return

  interrupt CL, OFF

  pause 10  ' debounce
  if pin(CL) = 1 then

    do
    loop until pin(DT) = 0

'    num = (pin(CL)<<2) OR pin(DT)
    num = pin(CL) << 2
    num = num OR pin(DT)
    if num = 0 then counter = counter + 1       ' clockwise
    if counter > maxPos then counter = maxPos   ' upper limit
    if num = 4 then counter = counter - 1       ' counterclockwise
    if counter < minPos then counter = minPos   ' lower limit

  endif

  interrupt CL, readCL

return

I just modified the code splitting in 2 the line "num = (pin(CL)<<2) OR pin(DT)" because for some reason it gives syntax error in ESP32 (versions 47 and 48), although it works perfectly in ESP8266 (versions 43 and 44)
encoder_R.jpg
I hope it is useful
You do not have the required permissions to view the files attached to this post.
Post Reply