Problems with rotary encoder

Hi,

I’m giving rotary encoders a go, but running into problems where when I turn the rotary encoder left or right, nothing is registering in the serial monitor at all.

I have a 3 pin rotary encoder (this one: Rotary Encoder - 20 step 20-step Rotary Encoder [ST079] - £1.19 : Bitsbox Electronic Components, Electronic Component Suppliers UK) I have connected up using a similar method to the one in this example: How to Build a Rotary Encoder Circuit with an Arduino

I have Pin 1 (left-hand pin) of the rotary encoder directly connected to D6 on the D1 mini and Pin 3 (right-hand pin) of the rotary encoder connected to D7 on the D1 Mini. Pin 2 (middle pin) of the rotary encoder is connected to ground.

I’m using the example sketch below to test:

#include <Arduino.h>

//Rotary encoder example

int val;
int encoder0PinA = 13; // D7 on wemos d1 mini
int encoder0PinB = 12; // D6 on wemos d1 mini
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() {
  // put your setup code here, to run once:
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    } else {
      encoder0Pos++;
    }
    Serial.print (encoder0Pos);
    Serial.print ("/");
  }
  encoder0PinALast = n;


}

You need to either enable the internal pullup resistors on the inputs or install an external pullup (10K) on the each of the inputs.

pinMode (encoder0PinA, INPUT_PULLUP);
pinMode (encoder0PinB, INPUT_PULLUP);

Without the pullups the pins float so the state is undetermined.

That’s worked. Thank you very much.