Wednesday, 10 July 2013

A Multiple Encoder Library For Arduino

Here is an Arduino library which allows you to connect and decode up to 5 rotary encoders. It is basically an extension of my original encoder library, which can only decode one encoder.

You can download the library here: https://github.com/frodofski/Encoder_Polling_V2

Here is the example sketch:

#include <EncoderV2.h>

const int pin_A = 4;  // Encoder input pins
const int pin_B = 5;
const int pin_C = 6;
const int pin_D = 7;

void setup()
{
  Serial.begin(9600);
  encoder_begin();  // Start the library
  attach_encoder(0, pin_A, pin_B);  // Attach an encoder to pins A and B
  attach_encoder(1, pin_C, pin_D);  // Attach another encoder to pins C and D
}

void loop()
{
  int dir_0 = encoder_data(0);  // First encoder
  int dir_1 = encoder_data(1);  // Second
  
  if(millis() > 10000)
  {
    detach_encoder(1);  // After 10 seconds, detach encoder 1 
  }
  
  if(dir_0 != 0)  // Check for rotation
  {
    Serial.print("Encoder 0: ");
    Serial.println(dir_0);
  }
  
  if(dir_1 != 0)  // Check for rotation
  {
    Serial.print("Encoder 1: ");
    Serial.println(dir_1);
  }
}

The library is super easy to use, as it has only four functions:

  • encoder_begin() starts the library by setting up timer2 (note: this may conflict with the tone library)
  • attach_encoder(encNum, pin_A, pin_B) attaches an encoder to pin_A and pin_B, and sets these pins as inputs. encNum can equal 0, 1, 2, 3, or 4, allowing for up to five rotary encoders. The library will now start polling those two input pins.
  • detach_encoder(encNum) will detach the input pins corresponding to that encoder, and it will stop polling those two input pins. The pins can now be used as regular io again.
  • encoder_data(encNum) returns the state of the specified encoder. It returns a 1 or -1 if the encoder has turned, depending on the direction of rotation. It will return a 0 if the encoder has not turned, or if there is no encoder attached to that particular encNum.

The library will store that last known direction of the rotary encoder, until the encoder_data() function has been called for that encoder. This allows you to run the main sketch at any speed, without having to worry about missing a step.


Finally, you may need to use a hardware debouncer for each of the input pins if your're not using an optical encoder, or if your mechanical rotary encoder is particularly bouncy.

No comments:

Post a Comment