igorantolic / ai-esp32-rotary-encoder

Easy implement rotary encoder to your application using microcontroler like ESP32
GNU General Public License v2.0
284 stars 70 forks source link

How to declare several rotary encoders #51

Closed lm42p closed 1 year ago

lm42p commented 1 year ago

Hello, thank you for your amazing work. I have a little question: I don't know how to implement/define several rotary encoder.

lm42p commented 1 year ago

I just managed it. The SW have to be on a PWM pin.

Here is a code exemple for two rotary encoders:

#include "AiEsp32RotaryEncoder.h"

#define ROTARY_ENCODER_A_PIN 27
#define ROTARY_ENCODER_B_PIN 26
#define ROTARY_ENCODER_BUTTON_PIN 32
#define ROTARY_ENCODER_STEPS 4
AiEsp32RotaryEncoder rotaryEncoder = AiEsp32RotaryEncoder(ROTARY_ENCODER_A_PIN, ROTARY_ENCODER_B_PIN, ROTARY_ENCODER_BUTTON_PIN, -1, ROTARY_ENCODER_STEPS);

#define ROTARY_ENCODER2_A_PIN 13
#define ROTARY_ENCODER2_B_PIN 35
#define ROTARY_ENCODER2_BUTTON_PIN 14
#define ROTARY_ENCODER2_STEPS 4
AiEsp32RotaryEncoder rotaryEncoder2 = AiEsp32RotaryEncoder(ROTARY_ENCODER2_A_PIN, ROTARY_ENCODER2_B_PIN, ROTARY_ENCODER2_BUTTON_PIN, -1, ROTARY_ENCODER2_STEPS);

void IRAM_ATTR readEncoderISR()
{
    rotaryEncoder.readEncoder_ISR();
    rotaryEncoder2.readEncoder_ISR();
}

void setup()
{
    pinMode(ROTARY_ENCODER_A_PIN, INPUT_PULLUP);
    pinMode(ROTARY_ENCODER_B_PIN, INPUT_PULLUP);

    pinMode(ROTARY_ENCODER2_A_PIN, INPUT_PULLUP);
    pinMode(ROTARY_ENCODER2_B_PIN, INPUT_PULLUP);

    Serial.begin(115200);
    rotaryEncoder.begin();
    rotaryEncoder.setup(readEncoderISR);
    rotaryEncoder.setBoundaries(0, 1000, false); //minValue, maxValue, circleValues true|false (when max go to min and vice versa)
    rotaryEncoder.setAcceleration(250);

    rotaryEncoder2.begin();
    rotaryEncoder2.setup(readEncoderISR);
    rotaryEncoder2.setBoundaries(0, 1000, false); //minValue, maxValue, circleValues true|false (when max go to min and vice versa)
    rotaryEncoder2.setAcceleration(250);

}

void loop()
{
    if (rotaryEncoder.encoderChanged())
    {
        Serial.println(rotaryEncoder.readEncoder());
    }
    if (rotaryEncoder.isEncoderButtonClicked())
    {
        Serial.println("button pressed");
    }

    if (rotaryEncoder2.encoderChanged())
    {
        Serial.println(rotaryEncoder2.readEncoder());
    }
    if (rotaryEncoder2.isEncoderButtonClicked())
    {
        Serial.println("button 2 pressed");
    }
}
igorantolic commented 1 year ago

Closing since success