LennartHennigs / ESPRotary

Arduino/ESP library to simplify reading rotary encoder data.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use 2 encoders?

classic-audio opened this issue · comments

I would like to use 2 encoders.
How can I implement this using your code?

I have found a solution.
Here is my code. (if somone else can make use of the solution).

// Rotory encoder for ESP8266
// Ref: https://github.com/LennartHennigs/ESPRotary

#include "ESPRotary.h";
/////////////////////////////////////////////////////////////////
#define rot1P1  D1       // menu
#define rot1P2  D2   

#define rot2P1  D5       // attenuator
#define rot2P2  D6  

#define clicStep   4   // this number depends on your rotary encoder 
#define Step       1 
#define rotmin     0

/////////////////////////////////////////////////////////////////
#define rot1max    6   // Menu 6 step
#define rot2max   60   // Attenuator 60dB
#define rot1def    3   // Default 1kHz sinus
#define rot2def    6   // Default -6dB
/////////////////////////////////////////////////////////////////

ESPRotary r1;  // menu
ESPRotary r2;  // attenuator
/////////////////////////////////////////////////////////////////

void setup() {
  Serial.begin(9600);
  delay(50);

  r1.begin(rot1P1, rot1P2, clicStep, rotmin, rot1max, rot1def, Step);
  r2.begin(rot2P1, rot2P2, clicStep, rotmin, rot2max, rot2def, Step);

  r1.setChangedHandler(rotate1);
  r2.setChangedHandler(rotate2);
  r1.setLeftRotationHandler(showDirection1);
  r1.setRightRotationHandler(showDirection1);
  r2.setLeftRotationHandler(showDirection2);
  r2.setRightRotationHandler(showDirection2);  
}

void loop(){
  r1.loop();
  r2.loop();
}

/////////////////////////////////////////////////////////////////
// on change
void rotate1(ESPRotary& r1) {
   Serial.println(r1.getPosition());
}
/////////////////////////////////////////////////////////////////
void rotate2(ESPRotary& r2) {
   Serial.println(r2.getPosition());
}
/////////////////////////////////////////////////////////////////

Hey @classic-audio,
thx for sharing. Yes, this is the way!

(Depending on what the encoders do, you could consider having only one handler for both. You can check in the function for the encoder that called it.)

Cheers
l.