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

Arduino Rotary Encoder: One Line Debounce Code

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() {
  ...

   while(rotating)
  {
    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
About these ads
  1. 2011/09/05 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
    2011/11/23 at 21:03

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

  3. fanpap
    2011/12/02 at 21:21

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

    You saved me!

    Greetings!

  4. BlogGeanDo
    2011/12/04 at 01:32

    Glad I saved the life of a rotary encoder :-)

  5. Anonymous
    2013/05/25 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

  1. 2011/05/14 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

Follow

Get every new post delivered to your Inbox.

Join 193 other followers