Home > Arduino, Code > Arduino Rotary Encoder: One Line Debounce Code

Arduino Rotary Encoder: One Line Debounce Code

October 29, 2010 Leave a comment Go to comments

When using a rotary encoder, I like to use an interrupt line to detect that it is being used. Using this approach, one can write the debounce code with a simple delay. In the code below, the interrupt routine simply sets a flag. Then the code waits for the “bouncing” to finish. Empirically this takes about one millisecond.  I used 2 milliseconds and I’ve tested the code with a rotary encoder WITHOUT any kind of hardware debouncing.

// Rotary encoder interrupt service routine
static boolean rotating=false;
void rotEncoder()
  rotating=true; // If motion is detected in the rotary encoder,
                 // set the flag to true

void setup() {

  // Attach Interrupts
  attachInterrupt(0, rotEncoder, CHANGE);  // ISR for rotary encoder

void loop() {

    delay(2);  // debounce by waiting 2 milliseconds
               // (Just one line of code for debouncing)
    if (digitalRead(4) == digitalRead(2))  // CCW
    else                          // If not CCW, then it is CW

    rotating=false; // Reset the flag

Note: The small Arduinos (Duemilanove, Uno, etc) only have two interrupt lines: pin 2 and pin 3
  1. September 5, 2011 at 03:08

    Actually any pins can be used for interrupts. Check the PinChangeInt interrupt library for more information. See http://www.arduino.cc/playground/Main/PinChangeInt

  2. Anonymous
    November 23, 2011 at 21:03

    Thank goodness for this, I’ve been trying to debounce my rotary encoder all night🙂

  3. fanpap
    December 2, 2011 at 21:21

    Thank you very much for this code!!! I was ready to burn my rotencoder to ashes!!!!

    You saved me!


  4. BlogGeanDo
    December 4, 2011 at 01:32

    Glad I saved the life of a rotary encoder🙂

  5. Anonymous
    May 25, 2013 at 16:53

    it is almost working here, cozz Im a newbie.. i dont know how to change this to digital input 9 and 10. cozz i have only this input free

  6. September 14, 2016 at 18:18

    Calandra Eckley

  7. September 14, 2016 at 19:06

    phone repair

  1. May 14, 2011 at 17:26

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s