Skip to content

Class Instantiation

Arnd edited this page Dec 13, 2016 · 5 revisions

EncoderClass(LeftPin,RightPin,PushPin,RedPin,GreenPin,BluePin);

The class instantiation requires 6 parameters to be set. The first three parameters must reflect actual pins, if the 3 LED lights are not used the parameter values can be set to 0.

The RotaryEncoder class uses hardware interrupts to detect rotation on the encoder as well as push button presses. Each Atmel processor has a specific set of pins which can be used for hardware interrupts so the selection is quite limited. The three pins used must be in the list below for the appropriate processor:

Board Digital Interrupt Pins
Uno, Nano, Mini, other 328-based 2, 3
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7
Zero All except 4
MKR1000 Rev.1 0, 1, 4, 5, 6, 7, 8, 9, A1, A2
Due, 101 all digital pins

The 3 pins used for the LED lights need to be PWM pins so that the lights can be set to varying levels of brightness and for the fade algorithm to work. While there are generally more PWM pins on Atmel processors than hardware interrupt pins, the selection here is also limited. The analog pins on the Atmel processors are 8bit so have a range from 0 to 255. Since this rotary encoder has a common cathode (+) for the LED lights, the 3 pins need to be driven to ground (analog value of 0) in order for the light to be on at full power and when the value is set to the maximum of 255 the LED is turned off.


Example:

#include <Encoder.h>                // Include Encoder library          //
const uint8_t  ROTARY_PIN_1   =  2; // Pin for left rotary encoder pin  //
const uint8_t  ROTARY_PIN_2   =  3; // Pin for right rotary encoder pin //
const uint8_t  PUSHBUTTON_PIN =  7; // Pin for pushbutton connector pin //
const uint8_t  RED_PIN        = 11; // Red LED PWM pin. This is grounded//
const uint8_t  GREEN_PIN      = 10; // Green LED PWM pin. Grounded      //
const uint8_t  BLUE_PIN       =  9; // Blue LED PWM pin. Grounded       //

// Instantiate the class using all of the pins defined in constants     //
EncoderClass Encoder(ROTARY_PIN_1, ROTARY_PIN_2, PUSHBUTTON_PIN, RED_PIN, 
                     GREEN_PIN, BLUE_PIN); 

void setup() {
  Serial.begin(115200);
  delay(1000);
} // of method setup()
 void loop(){
  static int last = Encoder.GetEncoderValue();
  if (Encoder.GetEncoderValue()!=last) { // If the reading has changed  //
    last = Encoder.GetEncoderValue();    // display the new value       //
    Serial.print("Encoder position is ");
    Serial.println(last);
  } // of if-then we have a changed value
} // of method loop()