#define ENCODER_PIN_A 9 // Pin connected to encoder A output #define ENCODER_PIN_B 8 // Pin connected to encoder B output #define ENCODER_BUTTON_PIN 0 #define LED_PIN 2 // the number of the LED pin volatile int encoderCount = 0; bool ledState = false; // the current state of the LED int buttonState; // the current reading from the input pin bool lastButtonState = false; // the previous reading from the input pin // the following variables are long because the time, measured in milliseconds, // will quickly become a bigger number than can be stored in an int. unsigned long lastDebounceTime = 0; // the last time the output pin was toggled unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(ENCODER_BUTTON_PIN, INPUT_PULLUP); pinMode(LED_PIN, OUTPUT); pinMode(ENCODER_PIN_A, INPUT); pinMode(ENCODER_PIN_B, INPUT); attachInterrupt(digitalPinToInterrupt(ENCODER_PIN_A), encoderISR, CHANGE); Serial.begin(9600); } void loop() { // Print the encoder count Serial.print("Encoder Count: "); Serial.println(encoderCount); delay(100); // Update every second // read the state of the switch into a local variable: int reading = digitalRead(ENCODER_BUTTON_PIN); // check to see if you just pressed the button // (i.e., the input went from LOW to HIGH), and you've waited long enough // since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonState) { buttonState = reading; // only toggle the LED if the new button state is HIGH if (buttonState == HIGH) { encoderCount = 0; ledState = !ledState; } } } // set the LED: digitalWrite(LED_PIN, ledState); // save the reading. Next time through the loop, it'll be the lastButtonState: lastButtonState = reading; } void encoderISR() { // Read the state of pin B if (digitalRead(ENCODER_PIN_A) == digitalRead(ENCODER_PIN_B)) { encoderCount++; } else { encoderCount--; } // Serial.print("Encoder Count: "); // Serial.println(encoderCount); }