How to use a Rotary Encoder with an Arduino - CODE EXPLAINED!

Поділитися
Вставка
  • Опубліковано 30 лис 2024

КОМЕНТАРІ •

  • @thomawhite
    @thomawhite Рік тому +3

    I know this is a little late in the game, but I thought this may help someone. I loaded your code onto an ESP32 DevKit1C. Used pin 14 as A and 15 as B. Worked well except that: (1) the first turn of the knob did not register (counter did not change) and (2) after any change of direction, the first turn did not register. The code I downloaded from github has a few "static" declarations under the "read_encoder" function. The first is: "static uint8_t old_AB = 3; // Lookup table index 3". I changed "uint8_t old_AB = 3" to "uint8_t old_AB = 4" and the problem on my ESP32 is now solved. To the author. Thank you so much for a great piece of code. Brilliant!

    • @mothunderz
      @mothunderz  Рік тому +3

      Thank you very much for your comment to the video! Have you tried to characterize the rotary encoder as I show in 4:26 of the video? My suspicion is that your rotary coder works exactly the other way around. In that case, the LEDs would be lit up in the resting position and switch off when you turn the encoder. Can you try to compile the code with "static uint8_t old_AB = 0;" -> does it work for your then as well?

  • @mrdrgonzo
    @mrdrgonzo Рік тому +3

    Whoever worked out the coding for increasing and decreasing is a genius

    • @mothunderz
      @mothunderz  Рік тому +2

      Yes, look-up tables are awesome 🙂

  • @col000r
    @col000r 7 місяців тому +4

    I came here just to figure out how to hook up a Rotary Encoder, but I got so much more! Thank you for this excellent tutorial!

  • @NotShanny
    @NotShanny 16 днів тому

    I have to watch the video again concerning the coding part , but thank you very much it's a very interesting approch .

  • @BenjaminParisi-o6b
    @BenjaminParisi-o6b 8 місяців тому +2

    I thought I had a pot, but instead I had a rotary encoder! You have unblocked my project with this helpful video. :) Thanks

  • @sophtware
    @sophtware 7 місяців тому +1

    This is still by far the best code for handling rotary encoders that are a little noisy. This code works flawlessly every time I use it. Thanks for sharing and posting this video.

  • @jesenzeng2335
    @jesenzeng2335 Рік тому +2

    thank you sir,Your video is the clearest one to explain the encoder state machine(the lookup table),I modified the code a little bit,When a tick check failed because of a large number of noise.Assume the enc value has been added to 2. If next turn direction was CCW,the enc value would be changed like 2-->1-->0-->-1,The counter value won't change even enc value changed 4 times,Your code clears the enc value to zero only when it>3 or

    • @mothunderz
      @mothunderz  10 місяців тому

      Thank you for your feedback and suggestion. A time-out makes a lot of sense.

    • @sparkuploader
      @sparkuploader 4 місяці тому

      Hi, where did you add the time-out? is it in the main loop or in the callback function?

  • @valked6485
    @valked6485 2 місяці тому

    Finally! Finally I found someone who clearly explain it! Thanks so much!

  • @MrBrownpotato
    @MrBrownpotato Місяць тому

    I've used it in a PID control thermostat project, works great - thank you!

  • @brendanbarbour8568
    @brendanbarbour8568 Рік тому +1

    Hi Mo...that code is very responsive and reliable. I may need to adjust the multiplier value for the fast rotation, but that should be straightforward. I plan on using this as part of a precision AC current Trip. I'm using a Current Transformer to sense the current, which drives a Precision Rectifier and a comparator. I'm using an MCP4725 12-Bit DAC to set the reference for the Comparator. The falling-edge of the comparator output, triggers a D-FF which drives a DPDT relay to isolate the supply being monitored. Keep up the good work and thank you.

    • @mothunderz
      @mothunderz  Рік тому

      Sounds like a very interesting project. Thank you for sharing!

  • @tedwaetford
    @tedwaetford Рік тому

    I have a bunch of different encoders I am using to build a flight sim avionics panel. I was using some button box code I found on the internet, and the encoders were not behaving as expected. Specifically some of them only triggered every second click. Testing the encoders as you detail here, I found that some of them don't behave as the one in your example. A and B both alternate low,high,low... for subsequents rest positions. So using your LED test, at the rest positions, the lights go on,off,on... not just off. So I have a mixture of encoder types, X2 and X1 or X4, not sure which. Now I need to figure out how to adapt this code to cater for the different types. Be useful if these types were mentioned in this video. Great video, I am new to this stuff and your video was the most comprehensive explanation I have found for a newbie like me.

    • @mothunderz
      @mothunderz  Рік тому

      Thank you for the feedback. When doing the LED test, turn the encoder very slowly to make sure you get it right. The creation of the look-up table would be a bit to long to add to this video, it can be tricky. Hope you get it to work!

  • @trailranger6602
    @trailranger6602 Рік тому +1

    Thanks for this video. I've been concentrating on becoming more fluent with encoders and steppers lately, and you've explained somethings that I haven't run across before. This is a very clear, concise and informational video. You have gained a subscriber 🙂

    • @mothunderz
      @mothunderz  Рік тому

      Great to hear! I am glad the video was insightful 👌

  • @stefanwinkler799
    @stefanwinkler799 Рік тому

    Excellent video Sir, very well explained, a real pleasure to watch. I will use your code for a stepper motor driven indexing head. However there is a tiny flaw: If you turn the knob really fast, you may end in a state where encval is +2 / -2 in the rest position and you need two clicks backward/forward to decrease/increase the counter by one. Just set old_AB = 3 after abs(encval) >= 4 to get bullet proof code 🙂

    • @mothunderz
      @mothunderz  10 місяців тому

      Thank you very much for your feedback. I had made an update in the final code download that also addresses this issue. Did you still experience the issue in this final version:
      github.com/mo-thunderz/RotaryEncoder
      Thank you for the feedback! (and sorry for my late reply, am swamped with work ATM)

  • @PostalPete
    @PostalPete 7 місяців тому

    This is the only code that worked perfectly. All others I found on the internet for me only worked 80% correctly...

  • @requiem4adreamc
    @requiem4adreamc Рік тому

    It works flawlessly. I tried different codes but they didn't work properly. Your code works perfect. Thanks :)

    • @requiem4adreamc
      @requiem4adreamc Рік тому

      I wrote down this comment before watching full video. But after watching full video i am more impressed. You did it professionally. Other videos which i watched were amateurish. Your code logis is way better. It is time to modify this code and hopefully make it work like a volume up/down thing :)

    • @mothunderz
      @mothunderz  Рік тому +1

      Thank you very much for your feedback! Yes, you can use this as well for volume control. Good luck with your project!

    • @requiem4adreamc
      @requiem4adreamc Рік тому

      @@mothunderz Thanks :)

  • @ottosteehouder5921
    @ottosteehouder5921 11 місяців тому

    Very helpful, I nearly gave up on my encoder but this works remarkably well. I need an position on a positional axis and previous designs struggled with all kinds of misreading's.
    Thank you for a very good explanation aswell.

    • @mothunderz
      @mothunderz  10 місяців тому

      Thank you very much for your feedback!

  • @marioptoledo
    @marioptoledo 4 місяці тому +1

    I dunno what to do! Im just using a rotary with the atmega328p chip, and then I make the pull up resistor circuit + filters but the values still bounce any time.

  • @airdedman3221
    @airdedman3221 Рік тому +1

    Great video, and very clear instructions. 😊

    • @mothunderz
      @mothunderz  10 місяців тому

      Thank you very much!

  • @SamuelKreyenbuehl
    @SamuelKreyenbuehl Рік тому +1

    Thanks for sharing the information! ❤
    Really helpful for my project I’m working on at the moment

    • @mothunderz
      @mothunderz  Рік тому

      Wonderful! Wish you all the best for your project!

  • @PostalPete
    @PostalPete 6 місяців тому

    Interesting, I have a large rotary encoder on small PCB with 5 pins and with the LED test it behaves exactly as the one in this video. However, one of the mouse scroll wheel rotary encoders (Huano S-10 from Amazon) LED 1 lights up, then LED 2 (both are now lit), and then they both go out at the same time. In the other direction it's like: both are lit, LED 2 goes out, LED 1 goes out. Weird. I wonder if I can modify this code to work with this particular rotary encoder, as I am trying to save space in my project and not use one of the larger encoders.

  • @clarkso65
    @clarkso65 Рік тому +3

    Great! You explained everything in detail. Thanks so much

    • @mothunderz
      @mothunderz  Рік тому

      You're welcome, glad the vid was insightful for you!

  • @stephanc7192
    @stephanc7192 4 місяці тому

    Great explanation

  • @Mathing
    @Mathing Місяць тому

    Very helpful, thanks!

  • @FGRFPV
    @FGRFPV 7 місяців тому

    Just wondering, maybe it's clearly stated and I'm just not getting it right now: What happens, if the user would change the direction mid-click? As in after 2 Statechanges he returns back to the starting point instead of completing the click? Thank you for the nice work, it helps a lot!

  • @Csmitty-uw3ke
    @Csmitty-uw3ke 7 місяців тому

    Any suggestions for how to convert the values this code puts out into degrees?

  • @victorleonets179
    @victorleonets179 Рік тому

    You save my time, thanks from Ukraine

  • @Paul122M
    @Paul122M Рік тому

    Excellent video as always!

  • @tcolliass
    @tcolliass 7 місяців тому

    is there a way to use the rotary encoder without the interrupt pins? or can the inputs be polled instead?

  • @aarriikknn33ll
    @aarriikknn33ll Рік тому

    Very inormative video! Thanks, you didnt miss a thing

  • @laenga6044
    @laenga6044 Рік тому

    So amazing. It almost feels like applying AI to a rotary encoder, and it works so well. Big thanks, and Jesus loves you.

    • @mothunderz
      @mothunderz  Рік тому +1

      Wow, thank you! You are very welcome

  • @charley408
    @charley408 Рік тому

    I've been trying to figure out what kind of switch my cycle selctor is on my GE front load washer. It doesn't look like a rotory switch. It's soldered to the board, mine had cold solder joints and separated from the board. The switch looks like one of these. It has 2 bigger pins holding it on, not sure if they do anything because I don't see they are in a circuit line. Theb there a 4 smaller pins off to the side. It has those clicks as you turn it.

    • @mothunderz
      @mothunderz  Рік тому

      Is it a rotary encoder? You can figure that out by checking if it turns infinity. Does it have a push button function? If it does the first step should be to figure out which pins are used for that function. You can do that with the short circuit detection function of a multi meter (the one that makes a sound when the two wires are connected). You find the right pins as it will make a sound when you pushed the rotary encoder. The same way you can figure out which pins are used for the rotary encoder -> by rotating very slowly. Then, like I do in 4:27 you connect a resistor and LED with 5V on one end to figure out how the encoder behaves. Good luck with your project!

  • @larbigueraiche6721
    @larbigueraiche6721 Рік тому

    Awesome video.

  • @GergelyDrCsany
    @GergelyDrCsany Рік тому

    Thank you so much for the video, the nice explanation and the code! :) This has solved my problem (having much of the mentioned noise in my signals) in one of my projects - I'm really grateful for that. :)
    Is there a way to do it without interrupts as well? - I'm planning to make another project in which I'd like to use 4 rotary encoders with an Arduino Pro Micro (having only 5 pins with interrupts support).

    • @mothunderz
      @mothunderz  Рік тому +1

      well, the main problem with implementing this code without interrupts will be that you will miss events and that will lead to laggy responses on the encoders. Why do you want to use an Arduino Pro Micro? I recommend using an ESP32. That has interrupts on all ports.

  • @Maan_Arora
    @Maan_Arora Рік тому

    Hey, i’m trying to make a steering wheel for racing games , can i do this and have it work in racing games?

    • @mothunderz
      @mothunderz  Рік тому

      Yes, for that a rotary encoder should be very useful.

  • @GapRecordingsNamibia
    @GapRecordingsNamibia Рік тому

    So, may I ask please, everyone does the rotary encoder and an Arduino uno. Could you please do a sketch using the encoder with isr and an Arduino nano EVERY the one that uses the ATMega 4809, I have not found one YT video using this MCU with an Encoder and for us normal none program savvy people this is really hard to try and figure out how it works from the 600 page MCU manual. Thank you.

    • @mothunderz
      @mothunderz  Рік тому

      Unfortunately I dont have a nano here to test it out with, but the next time I buy some equipment I will order a nano as well. However, why dont you use an ESP32? It is about the same price level, but way faster, has Ethernet and Bluetooth and all PINs support interrupts. That is why on the ESP32 you can use rotary encoders on any of the pins. If you really want to stick to the nano, why do you want to use isr? According to
      www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
      the nano has interrupts on pins:
      2, 3, 9, 10, 11, 13, A1, A5, A7
      is that not sufficient?

  • @joelloyd2936
    @joelloyd2936 Рік тому

    is there a way to do this with multiple encoders even though only pins 2 and 3 support interrupts?

    • @mothunderz
      @mothunderz  Рік тому +1

      If you want to use multiple rotary encoders you cannot use the same pins on the Arduino. You will have two use pins with interrupts per encoder. There are platforms such as the esp32 that support interrupts on all pins if you want to use many rotary encoders

    • @joelloyd2936
      @joelloyd2936 Рік тому

      @@mothunderz thanks for the reply I'll look into that

  • @flotshii8036
    @flotshii8036 Рік тому

    Idk if this is just with me, but if i turn the encoder in one direction, then in the other, it first increments and then starts decrementing the value. So it is like this: turn right: 1,2,3,4,5 turn left: 6,5,4,3,2,1

    • @mothunderz
      @mothunderz  Рік тому

      Sorry for my late reply, I briefly wanted to doublecheck the behavior myself. I just did with my Arduino if I turn the other direction it does not lag so turn right 1, 2, 3, 4, 5 then turn left 4, 3, 2, 1, 0. On 4:27 in the video I show a simple method to verify operation of the rotary encoder. Can you verify if your rotary encoder behaves the same way? Thank you

    • @flotshii8036
      @flotshii8036 Рік тому

      @@mothunderz Thanks for your reply. Yes my Encoder does work the same way. I can figure out the reason my encoder setup behaves this way. i am using a pi pico insted of an arduino, but this shouldnt matter i think.... Did you notice anyone else having the same issue? Thanks

    • @mothunderz
      @mothunderz  Рік тому

      Do you have another Arduino to double check? I dont have a pico, but could find online some differences. Have you for instance changed Serial into Serial1? Have you checked with different ports? See for instance:
      forum.arduino.cc/t/working-rotary-encoder-for-arduino-doesn-t-work-for-pico/1045042/18
      hope you can make it work!

    • @mariusjunkerkrabbe9225
      @mariusjunkerkrabbe9225 Рік тому

      @@flotshii8036 I have the same issue with my arduino Mega, did you figure it out?

    • @mariusjunkerkrabbe9225
      @mariusjunkerkrabbe9225 Рік тому

      Hmmm🤔 I did nothing but rewrite what I believe is the exact same code, and it suddently works.

  • @DuyLe-yh8nf
    @DuyLe-yh8nf 10 місяців тому

    that's excellent

  • @luiscastillejo9336
    @luiscastillejo9336 Рік тому

    excelente gracias

  • @almirmulaosmanovic3401
    @almirmulaosmanovic3401 Рік тому

    Can KY-040 work without VCC connected?

    • @mothunderz
      @mothunderz  Рік тому

      As discussed in the video only the GND, DT and CLK need to be connected for the rotary encoder. The + and SW are for the push buttons.

    • @almirmulaosmanovic3401
      @almirmulaosmanovic3401 Рік тому

      @MoThunderz I watched the video, and it was most helpful. My mistake was asking before watching the video in it's entirety however after doing some math it appears that connecting the + would make the encoder more precise as it has internal 10k ohm resistors rather than using Arduino's pull up ressitors. Either that or put external pull-up resistors. Either way, your video helped me a lot. Thank you for taking the time to answer me

    • @zanthor6789
      @zanthor6789 Рік тому

      @@almirmulaosmanovic3401 Sorry for missing your comment back to me. Yes, you can use external pull-ups, but for me the performance with the internal pull-ups was already excellent, therefore, I never had the need to add additional components.

  • @numeprenume512
    @numeprenume512 Рік тому +1

    mine prints only ???????????, no numbers.
    must be broken...

    • @joelloyd2936
      @joelloyd2936 Рік тому +2

      make sure the baud rate in the serial monitor is the same as in the code

    • @mothunderz
      @mothunderz  Рік тому +1

      Thanks for chiming in Joe! Yes, for this code pls make sure the baudrate is 115200 in the serial monitor. You can change that on the bottom of the monitor window

  • @MrEvildigga
    @MrEvildigga Рік тому +1

    your video is a little bit to quiet i have trouble hearing you even at max volume with my laptop

    • @mothunderz
      @mothunderz  Рік тому

      Thank you for your feedback. Yes, you are right, it seems I did not get the audio level right on the master when uploading this video, my apologies for that. Unfortunately UA-cam does not let me change the audio for this particular video anymore. I will make sure this does not happen again and look into re-uploading this video with better audio.

    • @MrEvildigga
      @MrEvildigga Рік тому

      @MoThunderz no worries m8 just crank it up next time 👍

    • @mothunderz
      @mothunderz  Рік тому

      @@MrEvildigga Thanks! Glad you could make it work 🙂

  • @dalerogers1134
    @dalerogers1134 Рік тому

    Thank you for making this video! I appreciate the time you put into it and the professional graphics. Very well done. I am building an Omni wheel platform and my coding skill level certainly needs a boost. Eventually I will put together enough good examples to succeed with my project. I am doing this in support of my omnidirectional standing wheelchair project, to perfect the steering. That project has Roboclaw motor controllers that eliminate the need for the basic coding to support its encoders. I am a rookie and it took me a huge chunk of time to incorporate encoders. In the future I want to use affordable motor controllers and use the sketch to do the encoder translation. HTTPS://ua-cam.com/video/uZXhxTZDqusU/v-deo.html. I’d like not to be a rookie forever.

    • @mothunderz
      @mothunderz  Рік тому

      Thank you for your comment, I am glad my video helped you increase your understanding of the Arduino. I wish you all the best with your project!

  • @egyrmexiq1
    @egyrmexiq1 Рік тому

    Great video, very explicit, thanks for your efforts.. Subscribed.!!

    • @mothunderz
      @mothunderz  10 місяців тому +1

      Thank you very much, well appreciated!

  • @TheUnofficialMaker
    @TheUnofficialMaker Рік тому

    man your audio is low. Why do so many YT's spend so much on video and then have low volume? Hard to listen to

    • @mothunderz
      @mothunderz  Рік тому

      My apologies - forgot to normalize the audio on this one. Unfortunately YT does not allow me to make any corrections, so will have to re-upload

  • @hagarelsayed7891
    @hagarelsayed7891 8 місяців тому

    tarsh

  • @randomdamian
    @randomdamian 10 місяців тому

    The mic is so bad, great informative video but the mic is extremly quiet... if I would play a song now it would blow out my hifi speakers. It's actually half the volume than other videos on youtube

  • @woodybaines1953
    @woodybaines1953 Рік тому

    Love this guys videos !! #1 subs provider -> Promo'SM!!

    • @mothunderz
      @mothunderz  Рік тому

      Thank you very much for your support!