Improved Arduino Rotary Encoder Reading

Содержание

license

Introduction: Improved Arduino Rotary Encoder Reading

Easy Arduino Menus for Rotary Encoders

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

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

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.


Источник: www.instructables.com