<p>I'm having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical <a href="http://no.farnell.com/1520815/passives/product.us0?sku=alps-ec12d1524401" rel="noreferrer">ALPS encoder</a>, and I'm using <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf" rel="noreferrer">Atmega168</a>.</p>

<p><strong>Clarification</strong></p>

<p>I have tried using an External Interrupt to listen to the pins, but it seems like it is too slow. When Pin A goes high, the interrupt procedure starts and then checks if Pin B is high. The idea is that if Pin B is high the moment Pin A went high, then it is rotating counter clock-wise. If Pin B is low, then it is rotating clock-wise. But it seems like the AVR takes too long to check Pin B, so it is always read as high. </p>

<p>I've also tried to create a program that simply blocks until Pin B or Pin A changes. But it might be that there is too much noise when the encoder is rotated, because this does not work either. My last attempt was to have a timer which stores the last 8 values in a buffer and checks if it is going from low to high. This did not work either.</p>

<p>I have tried scoping the encoder, and it seems to use between 2 and 4ms from the first Pin changes till the other Pin changes.</p>

[{'answer_id': 34788, 'author': 'Daniel Jennings', 'author_id': 3641, 'author_profile': 'https://Stackoverflow.com/users/3641', 'pm_score': 0, 'selected': False, 'text': "<p>What exactly are you having problems with? I assume you've been able to hook the pins of the encoder to your PIC as per the technical specifications linked on the Farnell page you gave, so is the problem with reading the data? Do you not get any data from the encoder? Do you not know how to interpret the data you're getting back?</p>\n"}, {'answer_id': 35126, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 4, 'selected': True, 'text': '<p>I have a webpage about <a href="http://www.ubasics.com/adam/electronics/doc/rotryenc.shtml" rel="nofollow noreferrer">rotary encoders and how to use them</a>, which you might find useful.</p>\n\n<p>Unfortunately without more information I can\'t troubleshoot your particular problem. </p>\n\n<p>Which microcontroller pins are connected to the encoder, and what is the code you\'re currently using to decode the pulses?</p>\n\n<p>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 <a href="http://www.farnell.com/datasheets/103465.pdf" rel="nofollow noreferrer">data sheet</a> indicates that it may take up to 3mS for the parts to stop bouncing and creating false outputs.</p>\n\n<p>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).</p>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 223386, 'author': 'monowerker', 'author_id': 30091, 'author_profile': 'https://Stackoverflow.com/users/30091', 'pm_score': 1, 'selected': False, 'text': '<p>Speed should not be a problem. Mostly all mechanical switches need debounce routines. If you wanna do this with interrupts turn off the interrupt when it triggers, start a timer that will turn it back on after a couple of ms. Will keep your program polling-free >:)</p>\n'}, {'answer_id': 257613, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<pre><code>/* into 0 service rutine */\nif(CHB)\n{\n  if(flagB)\n   Count++;\n  FlagB=0;\n}\nelse\n{\n  if(FlagB)\n   count--:\n  FlagB=0:\n}\n\n/* into 1 service rutine */\nFlagB=1;\n\n/* make this give to you a windows time of 1/4 of T of the encoder resolution\n   that is in angle term: 360/ (4*resolution)\n */\n</code></pre>\n'}, {'answer_id': 312420, 'author': 'Marius', 'author_id': 1585, 'author_profile': 'https://Stackoverflow.com/users/1585', 'pm_score': 3, 'selected': False, 'text': "<p>Adding an analog lowpass filter greatly improves the signal. With the lowpass filter, the code on the AVR was really simple.</p>\n\n<pre><code>       _________\n        |         |\n        | Encoder |\n        |_________|\n          |  |  |\n          |  |  |\n     100n |  O  | 100n  \n GND O-||-+ GND +-||-O GND\n          |     | \n          \\     /\n      3K3 /     \\ 3K3\n          \\     /\n          |     |    \nVCC O-/\\/-+     +-\\/\\-O VCC\n     15K  |     |  15K\n          |     |\n          O     O\n          A     B\n</code></pre>\n\n<p>Ah, the wonders of ASCII art :p</p>\n\n<p>Here is the program on the AVR. Connect A and B to input PORTB on the avr:</p>\n\n<pre><code>#include &lt;avr/io.h&gt;\n\n#define PIN_A (PINB&amp;1)\n#define PIN_B ((PINB&gt;&gt;1)&amp;1)\n\nint main(void){\n    uint8_t st0 = 0;\n    uint8_t st1 = 0;\n    uint8_t dir = 0;\n    uint8_t temp = 0;\n    uint8_t counter = 0;\n    DDRD = 0xFF;\n    DDRB = 0;\n    while(1){   \n    if(dir == 0){\n        if(PIN_A &amp; (!PIN_B)){\n            dir = 2;\n        }else if(PIN_B &amp; (!PIN_A)){\n            dir = 4;\n        }else{\n            dir = 0;\n        }\n    }else if(dir == 2){\n        if(PIN_A &amp; (!PIN_B)){\n            dir = 2;\n        }else if((!PIN_A) &amp; (!PIN_B)){\n            counter--;\n            dir = 0;\n        }else{\n            dir = 0;\n        }\n    }else if(dir == 4){\n        if(PIN_B &amp; (!PIN_A)){\n            dir = 4;\n        }else if((!PIN_A) &amp; (!PIN_B)){\n            counter++;\n            dir = 0;\n        }else{\n            dir = 0;\n        }\n    }else if(PIN_B &amp; PIN_A){\n        dir = 0;\n    }\n        PORTD = ~counter;\n    }\n    return 0;\n}\n</code></pre>\n\n<p>This code works unless you rotate the encoder really fast. Then it might miss a step or two, but that is not important, as the person using the encoder won't know how many steps they have turned it. </p>\n"}]
['https://Stackoverflow.com/questions/34735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1585/']