Hi, i'm developing a robot arm & have a problem with one of my encoders. when the motor turns, the encoder counts do not go up incrementally, they randomly jump up thousands at a time. the code below works with all other motors in my system but gives errors for some reason with this one.
i have switched motors, which doesn't help.
I isolated this code form my main program to test with (it gives the same problem outside of my main code as it does when its included)
can you see any possible reason why my encoder counts are going from 0-25000, to 75000 then 211000 & similar? I'm using an arduino Mega 2560
i'd think it could only possibly increment count2 1 at a time.
#include <digitalWriteFast.h>
#define encodPinA2 20
#define encodPinB2 2
volatile bool _Encoder2ASet;
volatile bool _Encoder2BSet;
volatile bool _Encoder2APrev;
volatile bool _Encoder2BPrev;
volatile long count2 = 0;
void setup() {
Serial.begin(115200); // baud rate
Serial.flush();
pinMode(encodPinA2, INPUT);
pinMode(encodPinB2, INPUT);
digitalWrite(encodPinA2, LOW);
digitalWrite(encodPinB2, LOW);
attachInterrupt(digitalPinToInterrupt(encodPinA2), rencoder2, CHANGE);
attachInterrupt(digitalPinToInterrupt(encodPinB2), rencoder2, CHANGE);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("count2 = ");
Serial.print(count2);
Serial.print(" ");
Serial.println();
}
void rencoder2() {
_Encoder2BSet = digitalReadFast(encodPinB2); library
_Encoder2ASet = digitalReadFast(encodPinA2);
count2 += ParseEncoder2();
_Encoder2APrev = _Encoder2ASet;
_Encoder2BPrev = _Encoder2BSet;
}
int ParseEncoder2() {
if (_Encoder2APrev && _Encoder2BPrev) {
if (!_Encoder2ASet && _Encoder2BSet) return 1;
if (_Encoder2ASet && !_Encoder2BSet) return -1;
} else if (!_Encoder2APrev && _Encoder2BPrev) {
if (!_Encoder2ASet && !_Encoder2BSet) return 1;
if (_Encoder2ASet && _Encoder2BSet) return -1;
} else if (!_Encoder2APrev && !_Encoder2BPrev) {
if (_Encoder2ASet && !_Encoder2BSet) return 1;
if (!_Encoder2ASet && _Encoder2BSet) return -1;
} else if (_Encoder2APrev && !_Encoder2BPrev) {
if (_Encoder2ASet && _Encoder2BSet) return 1;
if (!_Encoder2ASet && !_Encoder2BSet) return -1;
}
}