Hi All,
I am trying to get my rotary encoder to work for a future project i have in mind. What i want the encoder to do is print to serial the counts starting from 0 up to 10, then stop. then if i turn the encoder the opposite way it goes down back to 0 then stops. Much like a volume knob on an amplifier so you have a min and a max value.
The attached code somewhat works but it goes from 0-10 the gets stuck.
could somebody please have a look at my code and advise me where it is wrong.
Much appreciated
Thanks
// Rotary encoder example.
// Wiring: Connect common pin of encoder to ground.
// Connect pins A and B (the outer ones) to pins 2 and 3 (which can generate interrupts)
volatile boolean fired = false;
volatile long rotaryCount =0;
// Interrupt Service Routine
void isr ()
{
static boolean ready;
static unsigned long lastFiredTime;
static byte pinA, pinB;
// wait for main program to process it
if (fired)
return;
byte newPinA = digitalRead (2);
byte newPinB = digitalRead (3);
// Forward is: LH/HH or HL/LL
// Reverse is: HL/HH or LH/LL
// so we only record a turn on both the same (HH or LL)
if (newPinA == newPinB)
{
if (ready)
{
long increment = 1;
unsigned long now = millis ();
unsigned long interval = now - lastFiredTime;
lastFiredTime = now;
if (interval < 10)
increment = 5;
else if (interval < 20)
increment = 3;
else if (interval < 50)
increment = 2;
if (newPinA == HIGH)
{
if (pinA == LOW)
{
if (rotaryCount + increment <= 10)
rotaryCount + increment + 1;
}
else if (rotaryCount - increment >= 10)
rotaryCount --;
}
else
{
if (pinA == LOW)
{
if (rotaryCount - increment >= 10)
rotaryCount --;
}
else
{
if (rotaryCount + increment <= 10)
rotaryCount ++;
}
fired = true;
ready = false;
}
}
else
ready = true;
pinA = newPinA;
pinB = newPinB;
}
}
void setup ()
{
digitalWrite (2, HIGH); // activate pull-up resistors
digitalWrite (3, HIGH);
attachInterrupt (0, isr, CHANGE); // pin 2
attachInterrupt (1, isr, CHANGE); // pin 3
Serial.begin (9600);
} // end of setup
void loop ()
{
if (fired)
{
Serial.print ("Count = ");
Serial.println (rotaryCount);
fired = false;
} // end if fired
} // end of loop