Using a rotary encoder with AVR Micro controller

后端 未结 5 1203
小鲜肉
小鲜肉 2021-02-10 06:48

I\'m having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical ALPS encoder, and I\'m using Atmega168.

Cla

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-10 07:04

    I have a webpage about rotary encoders and how to use them, which you might find useful.

    Unfortunately without more information I can't troubleshoot your particular problem.

    Which microcontroller pins are connected to the encoder, and what is the code you're currently using to decode the pulses?

    Ok, you're dealing with a few different issues, the first issue is that this is a mechanical encoder, so you have to deal with switch noise (bounce, chatter). The data sheet indicates that it may take up to 3mS for the parts to stop bouncing and creating false outputs.

    You need to create a debounce routine. The simplest of which is to continuously check to see if A goes high. If it does, start a timer and check it again in 3 ms. If it's still high, then you can check B - if it's not high then you ignore the spurious pulse and continue looking for A high. When you check B, you look at it, start a timer for 3 ms, and then look at B again. If it was the same both times, then you can use that value - if it changes within 3 ms then you have to do it again (read B, wait 3 ms, then read it again and see if it matches).

    The atmega is fast enough that you shouldn't have to worry about these checks going slowly, unless you're also running a slow clock speed.

    Once you deal with the mechanical noise, then you want to look at a proper gray code routine - the algorithm you're following won't work unless you also decrement if A is high when B goes low. Generally people store the last value of the two inputs, and then compare it to the new value of the two inputs and use a small function to increment or decrement based on that. (Check out the heading "high resolution reading" on the website I mentioned above for the table). I combine the two readings into a four bit number and use a simple array to tell me whether I increment or decrement the counter, but there are solutions that are even more advanced, and optimize for code size, speed, or ease of code maintenance.

提交回复
热议问题