Hello,
I am quite new to Arduino, and i was just able to make one rotary encoder work. For my project, i am need 2 of them and i have tried expanding the "void isr" for the interupt, but i couldn't get it to wor.
I am using 2 ky040 rotary encoder arduino. Any help will be appreciated.
This is my code so far:
volatile boolean TurnDetected;
volatile boolean up;
const int PinCLK=2; // Used for generating interrupts using CLK signal
const int PinDT=4; // Used for reading DT signal
const int PinSW=7; // Used for the push button switch
const int PinCLK2=3; // Used for generating interrupts using CLK signal
const int PinDT2=6; // Used for reading DT signal
const int PinSW2=7; // Used for the push button switch
// Keep track of last rotary value
int lastCount = 50;
// Updated by the ISR (Interrupt Service Routine)
volatile int virtualPosition = 50;
void isr () {
static unsigned long lastInterruptTime = 0;
unsigned long interruptTime = millis();
// If interrupts come faster than 5ms, assume it's a bounce and ignore
if (interruptTime - lastInterruptTime > 5) {
if (digitalRead(PinDT) == LOW)
{
virtualPosition-- ; // Could be -5 or -10
}
else {
virtualPosition++ ; // Could be +5 or +10
}
// Restrict value from 0 to +100
virtualPosition = min(100, max(0, virtualPosition));
// Keep track of when we were here last (no more than every 5ms)
lastInterruptTime = interruptTime;
}
}
void setup() {
Serial.begin(115200);
// pinMode(SW_pin, INPUT);
// digitalWrite(SW_pin, HIGH);
// Rotary pulses are INPUTs
pinMode(PinCLK, INPUT);
pinMode(PinDT, INPUT);
// Switch is floating so use the in-built PULLUP so we don't need a resistor
pinMode(PinSW, INPUT_PULLUP);
// Attach the routine to service the interrupts
attachInterrupt(digitalPinToInterrupt(PinCLK), isr, LOW);
Serial.println("Start");
}
void loop() {
// Is someone pressing the rotary switch?
if ((!digitalRead(PinSW))) {
virtualPosition = 50;
while (!digitalRead(PinSW))
delay(10);
Serial.println("Reset");
}
// If the current rotary switch position has changed then update everything
if (virtualPosition != lastCount) {
// Write out to serial monitor the value and direction
Serial.print(virtualPosition > lastCount ? "Up :" : "Down:");
Serial.println(virtualPosition);
// Keep track of this new value
lastCount = virtualPosition ;
}
Serial.print("Status: ");
Serial.print(digitalRead(inPin));
Serial.print("\n");
Serial.print("X-axis: ");
Serial.print(analogRead(X_pin));
Serial.print("\n");
Serial.print("Y-axis: ");
Serial.println(analogRead(Y_pin));
Serial.print("\n\n");
delay (1000)
; }