Class object array

Status
Not open for further replies.

mtiger

Well-known member
Hi Guys,

Using the 'RotaryEncoder' library, by default the example shows instantiating one encoder which has two constructor parameters (pin A, pin B).

How would I use an array to instantiate 8 encoders and setup arrays so I don't have to copy all the code in the loop for each encoder I use. Please see attached code for reference. I've commented out the attempt of using an array, but that doesn't seem to work.

Also, here is the class on GitHub for further reference: https://github.com/mathertel/RotaryEncoder.

Any help would be great. :)

Code:
#include <RotaryEncoder.h>

#define ROTARYSTEPS 3
#define ROTARYMIN 0
#define ROTARYMAX 127

//RotaryEncoder encoder[8] = { {7,8} , {9, 10} };

RotaryEncoder encoder1(7, 8);

int newPosition = 0;
int lastPosition = 0;

void setup()
{
  Serial.begin(9600);
  //  encoder.setPosition(0 / ROTARYSTEPS); Start Position
}



void loop()
{
  encoder1.tick();

  newPosition = encoder1.getPosition() * ROTARYSTEPS;

  if (newPosition < ROTARYMIN) {
    encoder1.setPosition(ROTARYMIN / ROTARYSTEPS);
    newPosition = ROTARYMIN;

  } else if (newPosition > ROTARYMAX) {
    encoder1.setPosition(ROTARYMAX / ROTARYSTEPS);
    newPosition = ROTARYMAX;
  } // if

  if (lastPosition != newPosition) {
    Serial.print(newPosition);
    Serial.println();
    lastPosition = newPosition;
  }
}
 
Last edited:
You were close...this works:

Code:
#include "RotaryEncoder.h"

RotaryEncoder encoder[8] = {RotaryEncoder(7, 8),
                            RotaryEncoder(9, 10),
                            RotaryEncoder(11, 12),
                            RotaryEncoder(13, 14),
                            RotaryEncoder(15, 16),
                            RotaryEncoder(17, 18),
                            RotaryEncoder(19, 20),
                            RotaryEncoder(21, 22)};

void setup() {

}

void loop() {

}

There are also methods using new and pointers or using std::vector, but this approach is straightforward.
 
Status
Not open for further replies.
Back
Top