Introduction: Improved Arduino Rotary Encoder Reading

Picture of Improved Arduino Rotary Encoder Reading

Rotary encoders are great input devices for electronics projects - hopefully this Instructable will inspire and help you use one in your next project.

Why write rotary encoder code?

I wanted to use a low cost rotary encoder as an input mechanism for one of my upcoming projects and was initially bewildered by the code options available to take readings from the rotary encoder and determine how many "detents" or cycles the encoder had clicked past and in what direction. I think my main sketch will need to use most of my Arduino's memory so I am avoiding the various available encoder libraries, which seemed to be difficult to make work when I tried a couple of them. They also appear to use far more of the code budget than the sketch-based code approaches discussed from here on.

If you just want to bypass the thinking behind my approach and get straight into the Instructable, feel free to skip ahead to Step 1!

Other Approaches

Several of the main sketch-based (i.e. they don't use a library) approaches are discussed in rt's blog post where they write rotary encoder code that makes the cheapest encoders usable as Arduino inputs. They also have a good example of they logic signal that the encoder produces. rt found that a timer interrupt system worked best for them but I'm concerned that the polling frequency would detract from screen update speed in the main loop of my project sketch. Given that the rotary encoder will be moving for a tiny proportion of the time I want the screen to be updating, this seems a poor match for my application.

I chose to start off using Steve Spence's code here, which was fine on it's own but appeared to really slow down when I incorporated the rest of my sketch code (which involves writing display updates to a small TFT screen). Initially I wondered if it could be because the main loop contains a debounce statement.

I then read Oleg's rotary encoder article on an interrupt service routine version of his previous post, I also thought it might be a good idea to use direct port manipulation to read both pins simultaneously and as soon as the interrupt fires. His code can be used on any input pin if the port manipulation code is rewritten. In contrast, I decided to use only the hardware interrupts on digital pins 2 and 3, so we can set interrupts to only fire on a rising edge of the pin voltage, rather than on pin voltage change, which includes falling edges. This reduces the number of times the ISR is called, distracting from the main loop.

Oleg's code uses a lookup table to reduce compiled code size to a really small size but I couldn't get reliable results which would catch very slow rotation as well as reasonably fast rotation. Bear in mind that hardware debouncing (see Step 2) can help a lot with reliability of readings but I was after a software solution to simplify the hardware build and be as portable to other hardware applications as possible.

This concludes the introduction of my challenge and considerations. In Step 2 we'll take a look at the encoder hardware, terminology and some practical considerations when you want to integrate a rotary encoder into your project.

Step 1: A Bit About Rotary Encoders

Picture of A Bit About Rotary Encoders

Why are rotary encoders so cool?

  1. Unlike a variable resistor/potentiometer they have infinite travel in any direction and because they produce a digital "Gray code" you can scale their readings to whatever range you like.
  2. The dual direction makes them useful for increasing or decreasing a value within a variable or navigating menus.
  3. Finally, many of these rotary encoders come with a centre push button, which can be used to select menu items, reset a counter or do anything you can think of that might suit a momentary push button.

Terms

  1. PPR: pulses per rotation - typically 12, 20 or 24. You might also see specifications for maximum rotation in rpm etc. This is probably determined by the encoder's propensity to "bounce" contacts - see below.
  2. Detent: the little click of the action as it springs to a natural rest point between pulses. There may be one detent per pulse/cycle (not equal to a rotation of the shaft) or two.
  3. Bounce: mechanical contacts inside the encoder literally bounce enough to jump off and back on a contact when rotating, potentially leading to too many readings attributed to that phase of the travel between detents.
  4. Debounce: This can be either done in hardware, perhaps with a low value ceramic capacitor between each pin and Ground, or in software, perhaps with a delay. In either case, the aim is to create a system which ignores bouncing contacts.

Tips

  1. Look out for a threaded section near the base of the shaft and a matching nut if you want to mount your encoder in a panel or enclosure.
  2. Many knobs are available for rotary encoders, with the most easily available coming in 6mm diameter shafts.
  3. Pay attention to whether your encoder shaft uses a flat face or splines to achieve a proper fit with the knob.
  4. The body of the rotary encoder may also come with a raised pin/stub, intended to mate with a small indent/hole in your panel (probably hidden by your knob) and prevent your encoder from rotating when you turn the knob. You might find you want to remove this if you can create enough friction to prevent encoder body rotation using the mounting bolt to screw the encoder in the panel or enclosure.
  5. Make sure you find out where the detent state is for your encoder and adapt your code accordingly. My example uses an encoder whose pins are both disconnected from ground and are pulled high by their respective input pullup resistors. This drives my selection of a RISING interrupt. If both pins were connected to ground when at detent, they would need code which was looking for FALLING pin voltage.

Step 2: The Circuit

Picture of The Circuit

The circuit is so simple. You will need:



• An ATMEGA328P based Arduino, such as the Uno, Pro Mini or Nano.
• A mechanical (as opposed to optical) quadrature rotary encoder - this is the most common kind so don't worry too much if it isn't specified. eBay and Aliexpress listings will often mention Arduino in the description and this is a good indicator that one is suitable.
• Hook-up wire/jumper leads.
• Optional: a prototyping breadboard.


First of all, look for a collection of three pins on one side of the encoder. These are the three for measuring rotation with our code. If there are two pins together on another side, these are likely to be for the centre push button. We'll ignore these for now.

Out of the three pins together, the encoder ground pin is connected to Arduino ground pin. Either of the other two pins is connected to digital pin 2 and the remaining on is connected to digital pin 3. If your direction of rotation isn't the way you'd like, just swap the two non-ground pins over.

Pins 2 and 3 are important because on the ATMEGA328P-based Arduinos they are the only pins which have the ability to detect RISING and FALLING pin change interrupts. The MEGA 2560 boards etc. have other hardware interrupt pins which can do this.

Note: In the diagram the ground pin is one of the end pins. In reality, the ground pin is often the centre pin but this is not always the case so read the datasheet or test your encoder to find out which pin is ground.

Another note: ArneTR made a good comment about not having a separately wired connection to the logic positive voltage (e.g. 5V or 3.3V) for the rotary encoder circuit shown. The Arduino can't read the rotary encoder without both a ground signal (which we have connected a wire to) and the logic voltage (sometimes annotated as Vcc or Vdd), so how can the Arduino read the logic from this encoder without a positive voltage wire? The answer is that the ATMEGA328P chip in the Arduino has a special mode you can set on the digital pins (which we are using) where a pin is automatically pulled "high" to the logic voltage by an internal resistor. Look in the code for "pinMode(pinX, INPUT_PULLUP)" to see us telling the Arduino that we want to take advantage of this mode. Once set, we only need to provide the encoder with a ground wire as the sensing wires from the digital pins are already providing the logic voltage.

ONE MORE THING... Githyuk found that a particular branded encoder didn't work with this way of doing things (ie the code below). Please see the comments section for details but in general, trying a different encoder would be a good debugging step when you have exhausted the easier/faster/cheaper steps.

Step 3: The Code

If you are not familiar with programming Arduinos, please get up to speed with this resource from Arduino themselves.

This code is free for your use (as in no cost and to be modified as you please), please attribute where you should.


/*******Interrupt-based Rotary Encoder Sketch*******
by Simon Merrett, based on insight from Oleg Mazurov, Nick Gammon, rt, Steve Spence
*/

static int pinA = 2; // Our first hardware interrupt pin is digital pin 2
static int pinB = 3; // Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0; // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0; // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0; //somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent

void setup() {
pinMode(pinA, INPUT_PULLUP); // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
pinMode(pinB, INPUT_PULLUP); // set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
attachInterrupt(0,PinA,RISING); // set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
attachInterrupt(1,PinB,RISING); // set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
Serial.begin(115200); // start the serial monitor link
}

void PinA(){
cli(); //stop interrupts happening before we read pin values
reading = PIND & 0xC; // read all eight pin values then strip away all but pinA and pinB's values
if(reading == B00001100 && aFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
encoderPos --; //decrement the encoder's position count
bFlag = 0; //reset flags for the next turn
aFlag = 0; //reset flags for the next turn
}
else if (reading == B00000100) bFlag = 1; //signal that we're expecting pinB to signal the transition to detent from free rotation
sei(); //restart interrupts
}

void PinB(){
cli(); //stop interrupts happening before we read pin values
reading = PIND & 0xC; //read all eight pin values then strip away all but pinA and pinB's values
if (reading == B00001100 && bFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
encoderPos ++; //increment the encoder's position count
bFlag = 0; //reset flags for the next turn
aFlag = 0; //reset flags for the next turn
}
else if (reading == B00001000) aFlag = 1; //signal that we're expecting pinA to signal the transition to detent from free rotation
sei(); //restart interrupts
}

void loop(){
if(oldEncPos != encoderPos) {
Serial.println(encoderPos);
oldEncPos = encoderPos;
}
}

That's it!

Step 4: Conclusion

Picture of Conclusion

I hope you find this code useful for your next project which uses a rotary encoder or that it has inspired you to consider a rotary encoder as an input for your next project.

Summary of the Aims

I have tried to write some code which achieves a good balance of:

  • Portability (port manipulation code is the compromise when moving to other chips)
  • Speed (port manipulation really helps)
  • Low compiled code size (port manipulation and bitmath helps)
  • Reliably records slow and fast manual rotation
  • Reduced nugatory interrupt service routine calls (using RISING interrupt and temporarily disabling interrupts)

Caveats and Ideas for Improvement

This code isn't perfect by any means and you might like to change it to use other pins. I tested this code with the sketch which was causing the most delay and least reliable readings with the other approaches discussed - I certainly haven't compared it with timers to see whose code produces fewer nugatory interrupt service routines, takes the least time to execute or filters out the highest percentage of contact bounces. Perhaps someone might like to do a benchmark test against the other approaches out there.

Comments

kd6oji (author)2017-09-10

Thanks Simon, I am working on an LCD Menu and hunting some examples of the rotary encoder control, your code was rock solid in performance with my salvaged encoder. One thing I really enjoyed was that there were no 'glitchy' points as I've had with other examples.

SimonM83 (author)kd6oji2017-09-12

kd6oji, that's encouraging to hear and thanks for taking the time to let us know!

instruct-eric (author)2017-07-04

Hi Simon, I just recently acquired some EC11 rotary encoders and apart from wiring the middle pin to GND they work well with your code. I would be interested in a h/ware + s/ware approach to limit the processor workload. Nick Gammon is a brilliant experimenter in this area. Accolades to you and all the other gurus that inspired this Instructable

SimonM83 (author)instruct-eric2017-07-04

My electronics knowledge isn't great but you might be able to reduce the workload for the processor using an op amp as a comparator and/or (!) some logic gates. Perhaps some latching would be required. I'm not working on anything like this but if you find something, please post a link!

Bkukuk62 (author)2017-06-27

Hi Simon,

your encoder sketch works great with this encoder (OMRON E6B2-CWZ6C) on a Arduino Uno. I would like to get some assistance if I could to have this code work for my application. I am a Transmitter Hunter for a local Ham Radio Club and I have a beam that I want to track 0 to 360 degree rotation. I also have a Z-index on this encoder that I would like the routine to reset the counter to zero (Reset to zero) everytime it hits the z-index position. This will allow the encoder to stay accurate to the front of the vehicle this is mounted to. One more thing that would be great is an led that would blink everytime the z-index hit zero this led would blink. I am just learning arduino programming and any help I can get to accomplish this project would be greatly appreciated. Update, I have the 0 to 360 tracking working with no negative numbers. I also have the reset to zero button working so that the initial calibration for 0 (front of the vehicle) works. My issue now is the Z index portion (I gave it a shot but doesn't work) and getting the onboard LED to turn on when the encoder is around zero (Index position). This could be a +/- 3 degrees as zero would be hard to see all the time as it came around. here is the code so far:

//*******Interrupt-based Rotary Encoder Sketch*******

// Wiring connections for my encoder:

// Brown : VCC = 5 to 24VDC

// Blue: 0V(Common) = GND

// Shield: GND

// Black: outA = Digital pin 2

// White: outB = Digital pin 3

// Orange: outZ = Digital pin 4 (Index)

// buttonPinNr = Digital pin 5

// Onboard LED from digital pin 13 to ground for zero degree condition

// With these outA/outB/outZ connections and the interrupt code below

// clockwise rotation gives positive encoder counts

static int pinA = 2; // Our first hardware interrupt pin is digital pin 2

static int pinB = 3; // Our second hardware interrupt pin is digital pin 3

static int pinC = 4; // Our third hardware interrupt pin is digital pin 4

const int buttonPinNr = 5; //reset button to zero

volatile byte aFlag = 0; // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent

volatile byte bFlag = 0; // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)

volatile byte cFlag = 0; // let's us know when we're expecting a rising edge on pinC to signal that the encoder has arrived at a detent (Indexed location for zero(reset))

volatile int encoderPos = 0; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255

volatile byte oldEncPos = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)

volatile byte reading = 0; //somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent

void setup() {

pinMode(pinA, INPUT_PULLUP); // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)

pinMode(pinB, INPUT_PULLUP); // set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)

pinMode(pinC, INPUT_PULLUP); // set pinC as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)

pinMode(buttonPinNr, OUTPUT); //set buttonPinNR as output

attachInterrupt(0,PinA,RISING); // set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)

attachInterrupt(1,PinB,RISING); // set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)

attachInterrupt(2,PinC,RISING); // set an interrupt on PinC, looking for a rising edge signal and executing the "PinC" Interrupt Service Routine (below)

Serial.begin(115200); // start the serial monitor link

}

void PinA(){

cli(); //stop interrupts happening before we read pin values

reading = PIND & 0xC; // read all eight pin values then strip away all but pinA, pinB's & pinC's values

if(reading == B00001100 && aFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge

encoderPos --; //decrement the encoder's position count

if (encoderPos < 0)

{

encoderPos = (encoderPos + 360);

}

cFlag = 0; //reset flags for the next turn

bFlag = 0; //reset flags for the next turn

aFlag = 0; //reset flags for the next turn

}

else if (reading == B00000100) bFlag = 1; //signal that we're expecting pinB to signal the transition to detent from free rotation

sei(); //restart interrupts

}

void PinB(){

cli(); //stop interrupts happening before we read pin values

reading = PIND & 0xC; //read all eight pin values then strip away all but pinA, pinB's & pinC's values

if (reading == B00001100 && bFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge

encoderPos ++; //increment the encoder's position count

if (encoderPos >= 360)

{

encoderPos = (encoderPos - 360);

}

cFlag = 0; //reset flags for the next turn

bFlag = 0; //reset flags for the next turn

aFlag = 0; //reset flags for the next turn

}

else if (reading == B00001000) aFlag = 1; //signal that we're expecting pinA to signal the transition to detent from free rotation

sei(); //restart interrupts

}

void PinC(){

cli(); //stop interrupts happening before we read pin values

reading = PIND & 0xC; //read all eight pin values then strip away all but pinA, pinB's & pinC's values

if (reading == B00001100 && cFlag) { //check that we have pin C at detent (HIGH) and that we are expecting detent on this pin's rising edge

encoderPos = 0; //reset the encoders Z-Index to zero

cFlag = 0; //reset flags for the next turn

bFlag = 0; //reset flags for the next turn

aFlag = 0; //reset flags for the next turn

}

sei(); //restart interrupts

}

void loop(){

if (oldEncPos != encoderPos) {

Serial.println(encoderPos);

oldEncPos = encoderPos;

}

if (digitalRead(buttonPinNr) == HIGH){ //reset button to zero

encoderPos = 0;

}

}

Bkukuk62 (author)Bkukuk622017-06-30

I think I already discovered one flaw in my thinking with this sketch and that is trying to run this on an Arduino Uno because of the limitation of digital pins usable for interrupts (pins 2 & 3). I would be better off working with a Mega2560 that has 6 digital pins available (pins 2,3,18,19,20, 21). I would also like to be able to do a direct pin write of the 0 to 360 degree output (I believe would be 9 pins) to another Arduino for additional calculations and LED readout. Any thoughts? Bryan

SimonM83 (author)Bkukuk622017-06-30

Bryan, from what you've said I believe the Uno is absolutely capable of meeting your needs. Just use a Pin Change Interrupt (as per the Nick Gammon guide I linked to in my other reply) for the Z reset. You can use a display with an I2C or SPI interface if you want or set up a software serial pair of Rx/Tx pins to talk to another device (but I would like to think your further calculations can be done on the first Uno). Depending on your display interface, that will steer you to what pins remain for your Pin Change Interrupt. Keep at it. Even if you decide to order a Mega 2560, try the pin change interrupt on the Uno while you're waiting. You can even get a neopixel ring of colour changing leds and use those to display the angle of the encoder readout. That would only require one digital pin as well as power and ground. There's loads of guidance on neopixel and arduino on the Internet. Keep going!

SimonM83 (author)Bkukuk622017-06-28

Hi Bryan, thanks for posting in the comments. Before we get to your main issue, I want to say you've done a good job changing encoderPos to a larger size than a Byte but you might also want to change oldEncoderPos in the same way.

So, the problem is that you are trying to put a hardware interrupt on a pin which doesn't support it (digital pin 4). Only pins 2 and 3 support the kind of interrupt code we've used here. However, you can add pin change interrupts to the other pins (beware that it involves a whole port and therefore up to 8 pins - suggest you may want to look at using the analog pins if you want to reserve pin 13 as your LED pin. The best guide I know to all kinds of interrupts is by Nick Gammon (who is attributed in my code) and his section on pin change interrupts is here - good luck: http://gammon.com.au/forum/?id=11488&reply=6#reply6

nurochim (author)2017-06-01

hi Simon, im newbie in arduino.

can I use this code for reading 2 rotary encoder? i have try with mega2560 (pin 18,19 for encoder 1, then pin 20,21 for encoder 2) but not work. the code is exactly same with your post, just rename variable. i im very confused about it, can you please help me?

many thanks, Nurochim.

SimonM83 (author)nurochim2017-06-02

Hi Nurochim, this has been asked and answered partly in the comments below and the comments for my menu instructable. If you're a newbie and you want to make this work, you have a little bit of learning to do but that's great if you're doing this for a school project.

Here's the text from some relevant comments. You might need the datasheet for the ATMEGA2560 and/or a port manipulation guide and pinouts for the ATMEGA2560:

"Hi, I haven't tested this but I expect the reason it doesn't work directly with the mega2560 is because the interrupt service routine relies on port manipulation and the mega2560's hardware interrupt pins aren't on the same ports as the atmega328. My code above could be easily adapted for the mega2560 if you change PIND to the correct port, eg PINE, to read port E. It looks like arduino interrupt pins are on 2 and 3, which appears to equate to PE4 and PE5. That means you also need to change the B0000XX00 to bit shifting/ masking/ comparing B00XX0000 (PE0 will be the right hand bit, PE7 will be the left hand bit) to deal with the readings from your encoder. Good luck with the edit - I think it's definitely doable. Please post the code you change once you get it working so other people can use this on the mega2560"

"SuppeschluerferSimonM83Reply9 months ago
Mega 2560 - Pin 2(INT0) and 3(INT1):

PIND & 0xC change to PINE & 0x30
B00001100 change to B00110000
B00000100 change to B00010000
B00001000 change to B00100000"
nurochim (author)SimonM832017-06-04

thanks so much, it work on my project. but I still not understand with

B00001100 etc, what is the meaning of this code? and if I will use pin 20 and 21 for encoder, what should I change?

SimonM83 (author)nurochim2017-06-05

"B" means a binary number (Google if you want further explanation). The list of 1s and 0s after is a list of bits that make up a Byte. Each bit represents a pin on the microcontroller. The pins are grouped into "ports" which each have 8 pins, so a single binary Byte can represent the digital state of a whole port. To use code that commands the ports (called port manipulation), you have to find which port pins 20 and 21 etc are on. Eg they are on Port D. 21 is PD0, 20 is PD1 (goes in reverse). So in the byte which describes the whole of PortD, they are B000000(20)(21). Google for a "atmega 2560 pinout diagram" to check the pin assignment to ports if you don't want to look at the datasheet (which I do recommend). Then change the code which relates to port manipulation (B000XXXX, PIN(Y), PORT(Z) etc).

nurochim (author)SimonM832017-06-11

thanks so much simon, you help me to solve my problem.. thanks for your explanation,

SimonM83 (author)nurochim2017-06-12

Glad it made sense - looking back it wasn't the clearest explanation!

nathan2484 (author)2017-05-18

Hi Simon, This is a great inscrutable!! It is very thorougher and well explained.

I have everything working well with my project.

Could you explain how the rotary encoder reading rolls over, for example from 255 to 0? Would I be able to prevent this from happening? Keeping the reading at its max while being rotated positively until it is rotated in the opposite direction and the same for its min.

Many thanks, Nathan

nathan2484 (author)nathan24842017-05-18

Just found a solution to my problem based on what you said to someone else below. I added an if statement below where the encoder position is incremented or decremented to halt its progress.
Huge thanks again for this great guide! :)

SimonM83 (author)nathan24842017-05-18

nathan2484, well done for coming up with a solution!

Just for interest and in case you hadn't understood the cause of the number rolling over, if you look at the code, we declared the variable "encoderPos" as a byte. This just rolls over to 0 (or, in binary, 00000000) when you add 1 to 11111111 (ie 255) because if it were to be a 9 bit (as opposed to 8 bit) number it would tick over to 256 = 100000000. The 8 bit (1 byte) variable just ignores the 9th bit, reading from right to left, so we get back to 0. I hope I have explained that clearly enough.

Using an "if" statement is a good way to control the upper and lower values of your encoderPos variable. Thanks for your kind gratitude.

Ralphxyz (author)2017-05-13

Hi Simon, thank you for able, My encoder is a no name ebay encoder.

It works great for increment but does not decrement.

On increment every detent is counted on decrement sometimes one sometimes 2 sometimes 13 sometimes 23 detents are passed before a decrement shows up.

Depending on which wires to pin 2 and 3 I can get increment or decrement but not both.

Without decrement it is not really usable!

Ralph

SimonM83 (author)Ralphxyz2017-05-13

Ralphxyz, does this stay the same if you swap your wires around?

Ralphxyz (author)SimonM832017-05-14

Thank you Simon for the reply.

Yes, if I reverse the wires it is just the opposite, no increment.
It only works on every detent in one direction.

I tried with a different encoder, one that has no detents and every
full turn increments and decrements correctly.

Ralph

SimonM83 (author)Ralphxyz2017-05-14

Ralphxyz, I'm scratching my head on this one, as it's a directional issue that is at the encoder rather than the Arduino. Is there a chance that you have connected the wrong wire to Ground? Can you try different combinations of wiring?

Ralphxyz (author)SimonM832017-05-14

I have tried every wiring possibility.

And will do it again :-)

Ralph

Ralphxyz (author)Ralphxyz2017-05-14

Well it is working!!

Turns out the center pin was ground!!

Wooowee, thank you Sinom!!

SimonM83 (author)Ralphxyz2017-05-14

Amazing! I was just trying to think what to try next when I saw that you solved it. Well done!

Ralphxyz (author)SimonM832017-05-15

I "thought" I had tried every combination, but ...

It works great in both directions!!

I can turn the knob really fast and do not see any problems.

I do not appear to have any problem with bounce.

Thanks again for the 'able' .

Now I have to understand your code.

Ralph

SiDawg (author)2017-04-28

Thanks Simon! Great work. Works perfectly. For others reading: I did make a few changes.

I added two 100nF caps i.e. from A to Ground, and B to Ground
On my encoder (cheap aliexpress with switch) A and B are the outside pins: middle pin = Ground
I had to lower the buad rate to 9600: was getting nonsense characters on serial monitor.

All that aside: works perfectly! No bounce, perfect single steps on every detent no matter how fast I turn (turning manually at least!)

SimonM83 (author)SiDawg2017-04-30

SiDawg, glad to hear it's helped you and thanks for contributing to the community by posting your own findings.

RonVZ (author)2017-02-12

Hi Simon,

Thank you for your code, it works better than many others. Some others also work with attachInterrupt's but use other inputs. I've tried this code with other inputs, but that did not work. Question is, can this code be used for two rotary encoder's? I am using a Arduino UNO with ATMEGA328PU. Do you have an idea or example. Thanks in advance.

RonVZ

SimonM83 (author)RonVZ2017-04-30

RonVZ, I'm sorry I missed your comment. The code is specific to the two inputs as-written but I see no reason why you can't add a second encoder. You will need to add the extra interrupts and write the Interrupt Service Routine to read and process the Port reading relevant to the new encoder input pins. You should be able to get a clue about the microcontroller's handling of the bit-math by looking at the comments in the existing ISR code. Good luck and I hope this is still helpful.

sheetmetalalchemist (author)2016-09-19

Hi - I'm getting all kinds of errors trying to get this compiled. Any input?

'cli' was not declared in this scope
'PIND' was not declared in this scope
'sei' was not declared in this scope

Which board and IDE you using?

I'm on Arduino 1.6.11 using a Due over the programming port. Thanks!

If you look back at the decisions I made, one of the trade-offs was to use port manipulation to achieve speed. This unfortunately means that you would need to rewrite the code to make it work on boards that don't use the ATMEGA328P chip. Some people have done this for the ATMEGA2560 in these comments but that was the same "8 bit AVR" style as the ATMEGA328P so didn't require massive code changes. The Due is a "32 bit ARM" style of microcontroller and you'd need to look carefully into whether it can do something that is akin to port manipulation. The good news is that the Arduino community has probably worked this out already so you are only a few searches away from finding out how feasible editing the code is in this way. The other bonus of the Due is that it processes information much faster than the ATMEGA328P so you can probably just read each encoder pin in sequence without needing port manipulation in the first place. You'd have to work out how to compare the readings to determine whether you have passed a detent and in which direction but that's exactly what had to research when I decided to make this code. cli and sei are AVR instructions to turn interrupts off and on. I'm sure you can find a way of doing this with your Due. For example, the arduino functions nointerrupts() and interrupts() will probably do the trick and may have been a better way to write my own code but I wasn't sure if these functions would result in a larger sketch or slower execution when compiled so I went for the AVR commands to play it safe. Good luck and if you make a Due version of the code, please publish it for the benefit of others!

CrtSuznik (author)SimonM832017-04-27

Hey, I've been wrecking my head trying to figure out why the code worked on my UNO, but not on my MEGA. You wouldn't happen to have the mega version of the code, would you?

SimonM83 (author)CrtSuznik2017-04-27

Sorry, I got confused when I commented that other people had addressed the 2560 in these comments - actually it was in the comments on my rotary encoder menu instructable. Check out this awesome Instructable.

https://www.instructables.com/id/Easy-Arduino-Menus-for-Rotary-Encoders

If you scroll down to the comment by Suppeschluerfer there are suggestions for port (code) and pin settings on the 2560. I haven't tested it yet so it would be great if you could confirm if it worked.

AdamInAus (author)2017-01-10

Hi Simon,

This has been useful to me and I hate to nitpick,
but on entering an ISR function interrupts are already off, so there is
no need to turn them off, and turning them on at exit from your
function, though really not doing much harm, will lead to unnecessary
stack usage. And to be really pedantic you shouldn't turn them on, but
restore the original SREG state. But thank you all the same, it has been
interesting. The encoders I am using are so crappy that unfortunately
polling is a much better answer, but it has been an interesting journey.

Adam

SimonM83 (author)AdamInAus2017-01-10

Thanks for the simplifications. This is where a github repository would come in handy! Anyone with an account care to commit this code?

Sorry to hear about your encoders. I think the ones I tested with were no-name eBay specials so that's surprising. No joy if you change the debounce time?

AdamInAus (author)SimonM832017-01-10

At risk of being boring... I set up a sketch to log the events of CLK or DT going either high or low, and the log shows the time stamp of the event, the direction of the change, the state of the line that didn't change, and the microsecond time difference since the last event. What I found were many identical events which were high to low or low to high which directly followed each other, so the matching event had been missed even though the ISRs are short, the time difference being 8, 12 or 16 us (the granularity of the Uno being 4us). I ran it again on a Due and got the same result with smaller time differences, so even though I have capacitors in the circuit there are spikes lasting for very small times. What you end up with is odd and unpredictable interrupts taking unpredictable (and possibly excessive) amounts of time from the other processing, and you can't even work out what the signals mean. My encoders by the way are no-name eBay specials.

I'd post the logs and the sketches, but at the moment I haven't worked out how to do that nicely (a monospace font to make them readable).

My eventual solution was to assume that bouncing and spiking only happen when an electrical connection is (sort of) being made and the only thing you could trust was a high (detent on my hardware) signal, so polling and assuming that any noise in the polling debounce period indicates a signal has produced the best results for me. Very good actually, usable in fact which is not what I thought when I looked at the logs the first time.

Normally I am a big fan of interrupts, and deride polling, I wanted to believe in the interrupt driven solution, but I am a realist too, so for this application, polling it is.

dr_phil (author)2017-01-06

Excellent work Simon - thanks very much for sharing. Adding to Githyuk's observations, I have also found that this works well with a two detents per pulse encoder. I previously tried a KY-040 'module' with a 20 pulse/20 detent device, and performance was too jittery for a menu system. This is a bit of a shame as the 30/15 devices are relatively expensive (~£6 or more), especially if you want a switch and a threaded body. Now if we could just figure out how to get the cheapo ones to work... :-)

SimonM83 (author)dr_phil2017-01-06

That's a shame - I thought my encoder I used to test the system was a cheap one even though it was advertised as something better.

Githyuk (author)2016-12-10

Hello Simon,


For the life of me, I cannot seem to get a reading of B00000100 and therefore no flag that will increment in the CW direction. The CCW direction works awesome though, better than any code I've found so far. FWIW, I'm using the Bourns PEC 16-4215F-S0024 (24 detents, 24ppr).

http://www.digikey.ca/product-detail/en/bourns-inc...

https://www.bourns.com/pdfs/PEC16.pdf

Great tutorial so far, just banging my head trying to understand why my Rotary Encoder is not outputting the 0100 to raise the b flag.

SimonM83 (author)Githyuk2016-12-10

Hi Githyuk, sorry it's not working yet. Can you confirm that this behaviour is the same at low rotation speed? This would help rule out contact bounce. You could add some hardware debouncing to be sure.
From not knowing much about your setup (although encoder datasheet link was a good idea), I think there might be a situation where the other pin is always high when the other one triggers the interrupt. E.g, if you read B00001000, then you can get B00001100 but never B00000100 or B00000000. If this is the case, it could be a short circuit on the wiring to the pin, pulling it HIGH, or it could perhaps be that one of the Arduino pins is connected to the encoder ground pin. The data sheet didn't seem to be clear about which pins are A, B and ground (although it would be a good first assumption that a = A, b =B and c = ground. Perhaps check the wiring for pull-up short circuits and the try different combinations of encoder wiring. Hope that helps - post pictures if you have no joy.

Githyuk (author)SimonM832016-12-11

Ya, it doesn't matter how slow I go. I've tried it on two other encoders of the same model and I get similar results. Other encoder software does work somewhat in a CW direction, but not as smooth as yours in the CCW direction. May I ask what model of rotary encoder you used so I can look up it's spec sheet to compare quadrature output, or are all quad output encoders the same? Also, I have 1uf capacitors to contain debounce on both pins A and B. I did run a multimeter across the pins and have infinite resistance between all pins at detente. Thanks for your super quick response btw!

SimonM83 (author)Githyuk2016-12-11

Hmm, I used an Alps EC11B0924802 but I think the logic is all the same apart from whether the pins are grounded or not at detent. You might want to look at whether your reset is around B00001100 or B00000000. Other than that, I wonder if the capacitor is preventing the pin from reaching a 0 in sufficient time but I can't think what situation this could realistically occur in. Try without caps perhaps? Does it work in the same direction if you swap the arduino pins over?

Githyuk (author)SimonM832016-12-11

I did try reversing the pins and it counted up but not down.

Hmmm, your decoder has 2 detents/pulse whereas mine had 1d/p....wonder if that has something to do with it. Will try some diff decoders and get back to you. Thanks for the help thus far. Really want to use your code as I found it the smoothest by far.

Githyuk (author)Githyuk2016-12-16

Okay, my rotary encoders came in the mail today. Happy to report your code works flawlessly with the two detents per pulse over the one with the single detent per pulse. Maybe there is some weird timing issue going on, dunno. I sweated days over trying to figure out what went wrong. Letting you know in case you want to look at it with a different rotary encoder, or possibly just flag your instructees to the potential issue (not absolutely sure it is the detent per pulse thing, but ...). You can check it out for yourself I suppose if you haven't done so already. The new one I used today was ACZ09BR1E-20FA1-30C15P:

http://www.digikey.com/product-detail/en/cui-inc/A...

http://www.cui.com/product/resource/digikeypdf/acz...


Thanks again for your great code and public contribution. Cheers.

SimonM83 (author)Githyuk2016-12-17

Githyuk, thanks so much for the update - that's the kind of thing that will really help someone else who may be losing patience. I have edited the Instructable in Step 2 and signposted them to the details in your comments. So glad it's working well for you now!

Githyuk (author)SimonM832016-12-17

Thanks. I wouldn't say it so much a branded thing, than it is a detent thing...I'd be interested to know if any others used a one detent per pulse encoder as well. I am now using the PEC11R-4215F-S0012-ND which is the same company that made the first one I tried, however, this one has two detents per pulse and works beautifully. If anyone is reading this comment and has tried a one detent per pulse rotary encoder successfully, please let me know.

SimonM83 (author)Githyuk2016-12-17

Sorry, what I meant by branded was that it was a known part and therefore results should be repeatable (versus an unbranded eBay special). You're right to isolate the issue to the detent per pulse (although I'm not clear if it's 2 pulses per detent on the kind of encoder which works or 2 detents per pulse). Please show us the final results of your project.

chas1745 (author)2016-11-07

Hi Simon,

Thanks for what I hope will be a great start to a project where I need to input a number of variables for an extreme macro, stepper driven linear actuator.

Unfortunately, I a complete novice when it comes to coding and I am struggling to see how to display, on LCD, the text for the 'main menu' options. I can see that encoderPos give the numerical value for the Mode, but how do I translate this to a textual description? e.g. I need to display encoderPos = 2 as "Configure Stepper" so that as user I can see exactly what I am about to change.

Any insight would be much appreciated - my elderly brain not what it used to be!!

Charles