Hey Guys,
I never used an Arduino Due before so my knowledge about this specific board is basically zero.
I´ve copied some code for an Encoder from a blog post (Debounced Rotory Encoder – AZ-Delivery) and modified it slightly.
The code runs perfectly fine on my Arduino UNO and the LED Lights up every time I rotate the Encoder one notch but on my Arduino Due, which I need because I want to connect 6 Encoders in the end, the code just won´t work.
All wires are hooked up the same way on booth Arduinos.
I hope someone has an idea of what´s going wrong.
Here is my code:
#define encoderPinA 2
#define encoderPinB 3
#define SW 4
#define LED 8
volatile unsigned int encoderPos = 0; // a counter for the dial
unsigned int lastReportedPos = 1; // change management
static boolean rotating = false; // debounce management
int button = LOW;
int old_button = LOW;
// interrupt service routine variables
boolean A_set = false;
boolean B_set = false;
void setup()
{
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
pinMode( SW, INPUT_PULLUP );
pinMode(LED, OUTPUT);
digitalWrite(encoderPinA, HIGH); // turn on pullup resistors
digitalWrite(encoderPinB, HIGH); // turn on pullup resistors
attachInterrupt(0, doEncoderA, CHANGE); // encoder pin on interrupt 0 (pin 2)
attachInterrupt(1, doEncoderB, CHANGE); // encoder pin on interrupt 1 (pin 3)
/*
Serial.begin(9600); // output to PC Serial Monitor
delay(50);
Serial.println("System Ready");
delay(100);
*/
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}
void loop()
{
digitalWrite(LED, LOW);
//Serial.println("Entering Loop");
//delay(50);
rotating = true; // reset the debouncer
if (lastReportedPos != encoderPos)
{
actionPosition();
lastReportedPos = encoderPos;
}
button = !digitalRead( SW );
if ( button != old_button )
{
actionButton();
delay( 10 );
old_button = button;
}
//Serial.println("Leaving Loop");
//delay(50);
}
void actionButton()
{
/*
Serial.print("Button: ");
delay(50);
Serial.print ( button );
delay(50);
Serial.print (" | ");
delay(50);
Serial.println(encoderPos, DEC);
delay(50);
*/
}
void actionPosition()
{
/*
Serial.print("Position: ");
delay(50);
Serial.print(encoderPos, DEC);
delay(50);
Serial.print (" | ");
delay(50);
Serial.println ( button );
delay(50);
*/
digitalWrite(LED, HIGH);
}
// ISR Interrupt on A changing state (Increment position counter)
void doEncoderA()
{
if ( rotating ) delay (1); // wait a little until the bouncing is done
if ( digitalRead(encoderPinA) != A_set ) // debounce once more
{
A_set = ! A_set;
// adjust counter +1 if A leads B
if ( A_set && ! B_set )
encoderPos += 1;
rotating = false; // no more debouncing until loop() hits again
}
}
// ISR Interrupt on B changing state, same as A above
void doEncoderB()
{
if ( rotating ) delay (1);
if ( digitalRead(encoderPinB) != B_set )
{
B_set = ! B_set;
//adjust counter -1 if B leads A
if ( B_set && ! A_set )
encoderPos -= 1;
rotating = false;
}
}
Edit:
It seems like the code gets stuck inside of the Interrupt.