Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By beic
#77091 Hi there,

I'm trying to adopt the sketch bellow to work with my WeMos D1 mini and the well known Rotary Encoder KY-040, but it's not working for some reason, but the same sketch is working fine on the Arduino Uno (with different pin assigment).

Can someone tell me what is the issue with the sketch?

Thank you!

Code: Select allconst int PinA = 14; // Used for generating interrupts using CLK signal
const int PinB = 12; // Used for reading DT signal
const int PinSW = 13; // Used for the push button switch


int lCnt = 0; // Keep track of last rotary value
volatile int vPos = 0; // Updated by the ISR (Interrupt Service Routine)

void isr_event ()  {
  static unsigned long lIsrTmr = 0; // Last Interrupt time
  unsigned long IsrTmr = millis(); // Interrupt time

  // If interrupts come faster than 5ms, assume it's a bounce and ignore
  if (IsrTmr - lIsrTmr > 5) {
    if (digitalRead(PinB) == LOW)
    {
      vPos++ ; // Could be +5 or +10
    }
    else {
      vPos-- ; // Could be -5 or -10
    }

    // Restrict value from 0 to +100
    vPos = min(10, max(0, vPos));

    // Keep track of when we were here last (no more than every 5ms)
    lIsrTmr = IsrTmr;
  }
}

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

  // Rotary pulses are INPUTs
  pinMode(PinA, INPUT);
  pinMode(PinB, INPUT);

  pinMode(PinSW, INPUT_PULLUP); // Switch is floating so use the in-built PULLUP so we don't need a resistor

  attachInterrupt(digitalPinToInterrupt(PinA), isr_event, LOW); // Attach the routine to service the interrupts

  Serial.println(F("Starting..."));  // Ready to go!
}

void loop()
{

  // Is someone pressing the rotary switch?
  if ((!digitalRead(PinSW))) {
    vPos = 0;
    while (!digitalRead(PinSW))
      delay(10);
  }

  // If the current rotary switch position has changed then update everything
  if (vPos != lCnt) {
    // Write out to serial monitor the value and direction
    Serial.println(vPos);
    // Keep track of this new value
    lCnt = vPos ;
  }
}