I am working towards debouncing my keyes rotary encoder using the Bounce2 library found here ( https://github.com/thomasfredericks/Bounce2 ).
I believe the problem lies in my code as there isn't much in terms of a circuit. The encoder is connected to my arduino as follows
- 5V : connected to 5v out on arduino
- GND : connected to GND
- SW : connected to pin A1
- DT : connected to pin 3
- CLK : connected to pin 2
I am trying to call an ISR from a CLK input. When the ISR is called it should increment or decrement a value based on the direction the encoder was turned. This encoder is tied to an ISR because it will be used for user input and I would like it to remain responsive throughout the sketch.
Previously, I was using millis() to debounce the encoder, but I was still having trouble receiving more than one input from the encoder. I was hoping that this libary would resolve this issue.
The current output of the code I have included never increments/decrements the starting value no matter which direction the encoder is turned. In short, it always outputs 0.
If someone could explain what I am doing wrong that would be wonderful! Then maybe, but just maybe, I can stop beating my head against my desk. :p
Thanks, Kevin
#include <Bounce2.h>
#define sw A1
#define LED_PIN 9
#define clk 2
#define dt 3
int ledState = LOW;
int onOff = LOW;
volatile int virtualPosition = 0;
int lastCount = 0;
// Initiate bounce objects
Bounce debouncerSW = Bounce();
Bounce debouncerROT = Bounce();
void setup() {
Serial.begin(115200);
pinMode(sw, INPUT_PULLUP);
pinMode(clk, INPUT);
pinMode(dt, INPUT);
pinMode(LED_PIN, OUTPUT);
// set up button instace
debouncerSW.attach(sw);
debouncerSW.interval(100);
// set up rotary encoder instance
debouncerROT.attach(clk);
debouncerROT.interval(10);
// setup the LED
digitalWrite(LED_PIN, ledState);
// attach ISR
attachInterrupt(digitalPinToInterrupt(clk), isr, LOW);
Serial.println("Start"); // just to let me know sketch has finished setup
}
void loop() {
debouncerSW.update();
if ( debouncerSW.fell() ) {
ledState = !ledState;
onOff = !onOff;
digitalWrite(LED_PIN, ledState);
//read-outs
Serial.print("onOff = ");
Serial.println(onOff);
}
virtualPosition = lastCount;
//read-outs
Serial.print ("lastCount = ");
Serial.println (lastCount);
delay(1000); // for readability / simulates delay time for rest of main sketch
} // end main loop
void isr () {
// Update the Bounce instance :
debouncerROT.update();
if (debouncerROT.fell()) {
if (digitalRead(dt) == 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));
}
} // end ISR