Rotary encoder step to toggle on/ off

Hi, I want to toggle on/ off value using the step of rotary encoder. So that for one step ahead I can have ON and in the next step I can have OFF, and it will continue as i go ahead.

May I have any sample code to work on.

  1. Connect the rotary encoder
  2. Choose a component to control
  3. Read the encoder state
  4. Count steps
  5. Implement toggle logic
  6. Update output

Here is the sample code:

const int encoderPinA = 2;
const int encoderPinB = 3;
const int ledPin = 13;

volatile int encoderPos = 0;
boolean ledState = LOW;

void setup() {
  pinMode(encoderPinA, INPUT_PULLUP);
  pinMode(encoderPinB, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);

  attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
}

void loop() {
  // Other code here
}

void updateEncoder() {
  int MSB = digitalRead(encoderPinA);
  int LSB = digitalRead(encoderPinB);

  int encoded = (MSB << 1) | LSB;
  int sum = (encoderPos << 2) | encoded;

  if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderPos++;
  if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderPos--;

  if (encoderPos % 4 == 0) {  // Toggle on every 4 steps
    ledState = !ledState;
    digitalWrite(ledPin, ledState);
  }
}

1 Like

Keep it simple, you can use either output to toggle a port pin on your Arduino, then treat it like a push button (push on, push off). I am assuming you are using something like the KY-040 rotary encoder.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.