My project needed a dual rotary encoder so I purchased one but I can't get it working the way I want.
I have only the smaller inner knob wired up. The push switch works fine.
However, when I turn the inner knob two things are happening which I don't want to happen:
1. My debug serial println shows the 'cw' direction on every other click, instead of on every click. I want each click to fire the 'cw' path.
2. Regardless of which direction I turn the inner knob, it always follows the same path, thus I never see the 'ccw' path. I need to be able to detect either direction, with each click.
Thank you for any help.
I have only the smaller inner knob wired up. The push switch works fine.
However, when I turn the inner knob two things are happening which I don't want to happen:
1. My debug serial println shows the 'cw' direction on every other click, instead of on every click. I want each click to fire the 'cw' path.
2. Regardless of which direction I turn the inner knob, it always follows the same path, thus I never see the 'ccw' path. I need to be able to detect either direction, with each click.
Thank you for any help.
Code:
unsigned long currentTime;
unsigned long loopTime;
const int pin_A = 3; // pin 3
const int pin_B = 4; // pin 4
const int encoderSwitchPin = 5; //push button switch
unsigned char encoder_A;
unsigned char encoder_B;
unsigned char encoder_A_prev=0;
void setup()
{
Serial.begin (9600);
while (!Serial & millis() <4000)
{
}
Serial.println("starting");
pinMode(pin_A, INPUT_PULLUP);
pinMode(pin_B, INPUT_PULLUP);
pinMode(encoderSwitchPin, INPUT);
digitalWrite(pin_A, HIGH); //turn pullup resistor on
digitalWrite(pin_B, HIGH); //turn pullup resistor on
digitalWrite(encoderSwitchPin, HIGH); //turn pullup resistor on
currentTime = millis();
loopTime = currentTime;
}
void readEncoders()
{
if (digitalRead(encoderSwitchPin))
{
//button is not being pushed
}
else
{
//button is being pushed
Serial.println("pushed");
delay(500);
}
currentTime = millis();
if (currentTime >= (loopTime + 5))
{
encoder_A = digitalRead(pin_A);
encoder_B = digitalRead(pin_B);
if ((!encoder_A) && (encoder_A_prev))
{
// A has gone from high to low
if (encoder_B)
{
// B is high so clockwise
Serial.println("cw");
}
else
{
// B is low so counter-clockwise
Serial.println("ccw");
}
}
encoder_A_prev = encoder_A; // Store value of A for next time
loopTime = currentTime; // Updates loopTime
}
}
void loop()
{
readEncoders();
}