If you provide complete information as recommended by the forum,
(" How to get the best out of this forum),
you will have a better chance of getting help.
Post a schematic of your project;
Which Arduino are you using?
How your project should work.
BTW, if using UNO/Nano/Mini, the interrupt pin are 2 and 3.
Not 3 and 4.
encoderPinA = 3,
encoderPinB = 4,
digitalWrite(encoderPinA, HIGH); // turn on pullup resistor
digitalWrite(encoderPinB, HIGH); // turn on pullup resistor
PS:
Try this code:
enum PinAssignments {
encoderPinA = 3,
encoderPinB = 2,
clearButton = 8
};
volatile unsigned int encoderPos = 1;
unsigned int lastReportedPos = 1;
boolean A_set = false;
boolean B_set = false;
void setup() {
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
pinMode(clearButton, INPUT);
digitalWrite(encoderPinA, HIGH); // turn on pullup resistor
digitalWrite(encoderPinB, HIGH); // turn on pullup resistor
digitalWrite(clearButton, HIGH);
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(0, doEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
attachInterrupt(1, doEncoderB, CHANGE);
Serial.begin(9600);
}
void loop() {
if (lastReportedPos != encoderPos) {
Serial.print("Index:");
Serial.print(encoderPos, DEC);
Serial.println();
lastReportedPos = encoderPos;
}
if (digitalRead(clearButton) == LOW) {
encoderPos = 1;
}
}
// Interrupt on A changing state
void doEncoderA() {
// Test transition
A_set = digitalRead(encoderPinA) == HIGH;
// and adjust counter + if A leads B
encoderPos += (A_set != B_set) ? +1 : -1;
if(encoderPos < 1) encoderPos = 300;
}
// Interrupt on B changing state
void doEncoderB() {
// Test transition
B_set = digitalRead(encoderPinB) == HIGH;
// and adjust counter + if B follows A
encoderPos += (A_set == B_set) ? +1 : -1;
if(encoderPos > 300) encoderPos = 1;
}