I have a Pololu 4x encoder and am trying to write some code to make it work on my Nano 33 BLE. (Interestingly enough, the issue preventing some pre-existing libraries from working for me is the same issue that I'm about to describe here...)
When I turn the motor shaft clockwise, these are the signals that I get (first bit in each line is channel A, second bit channel B):
11 -> 10 -> 11 -> 10 -> 11 -> 10
Note how channel A's value never changes, and B's value toggles back and forth.
Likewise, for the counterclockwise direction:
01 -> 11 -> 01 -> 11 -> 01 -> 11
This is of course wrong, as the channels' values should be something like 00 -> 10 -> 11 -> 01 -> 00 as the shaft turns. As a matter of fact, that is exactly what I get when I run the exact same code on a regular Arduino Nano.
Does anyone know what's going on? Here's my code. AFAIK I'm not using interrupts incorrectly or anything, at least on the regular Nano.
#define PIN_A 2
#define PIN_B 3
volatile int val = 0;
volatile bool newVal = true;
void encoder() {
int a = digitalRead(PIN_A);
int b = digitalRead(PIN_B);
val = ((a << 1) | b);
newVal = true;
}
void setup() {
Serial.begin(57600);
pinMode(PIN_A, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, CHANGE);
pinMode(PIN_B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_B), encoder, CHANGE);
}
void loop() {
if (newVal) {
Serial.print(bool(val & 0b10));
Serial.print(bool(val & 0b01));
Serial.println();
newVal = false;
}
}