Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: Class object array

  1. #1

    Class object array

    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 by mtiger; 12-12-2017 at 12:49 AM.

  2. #2
    Senior Member brtaylor's Avatar
    Join Date
    Mar 2016
    Location
    Portland, OR
    Posts
    343
    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.

  3. #3
    Ahh thank you. I knew I was close, always missing the linking piece. Appreciate it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •