Easy Arduino Menus for Rotary Encoders




Intro: Easy Arduino Menus for Rotary Encoders

Rotary encoders with centre-push buttons are cool input hardware for projects, especially if you want to be able to scroll through menus and select options. Hopefully this Instructable will give you the confidence to try a basic menu system out and combine it with a rotary encoder to give a professional feel to your next project!

Why menus and rotary encoders need code

I wanted to have a menu in an upcoming project and use a rotary encoder with a centre push button as my input hardware. This is really similar to the LCD controllers for RAMPS and Arduino MEGA 3D printers. The rotary encoder will allow me to scroll through the menu options, i.e. navigate the menu, select sub-menus and also change values within sub-menus/settings - very versatile for one hardware interface! A microcontroller is needed to manage all of this and microcontrollers need instructions, AKA code!

Other options

The problem I had with existing Arduino menu libraries and menu code is that for simple menus they were overly complicated. Another drawback of many alternatives was that the code was designed for LCD screens and momentary push buttons, not rotary encoders and adaptable to other display outputs. These menus were geared around selecting between a small number of modes and incrementing values relatively slowly. We know that rotary encoders are a great hardware input option because they afford relatively fast input value changes while retaining fine control at slow speed. I wanted to write code which would allow unambiguous top level menu navigation but also allow you to quickly scroll through a large range of values within each sub-menu/setting, exploiting the strengths of the rotary encoder.

The approach

I decided to follow some advice to use if() statements for a simple menu structure and keep it sketch-based. The resultant code builds on my previous Instructable which sought to reliably read the rotation pulses and direction. Please check it out for background.

In this sketch, we add the reading of the centre push button on the rotary encoder shaft, using code that Nick Gammon developed to record button state changes with debouncing and without relying on the Arduino's delay() function that prevents the microcontroller from executing other code and would potentially introduce noticeable delay in our sketch, e.g. slow display refresh rates. Button state change code is much more useful than just reading digital logic high or low when using a button to select something once, like a menu option, as it can help you prevent unintentional multiple selections for each button press.

Let's take a look at what you need to set up to use this example code in Step 1.

Step 1: Preparation

If you haven't yet, please see my other Instructable on rotary encoder reading to find out how to set up your hardware and Arduino IDE software.


The additional hardware connections you need to make use of centre push button are shown in the pictures. I used Fritzing to draw the diagram but it didn't have a rotary encoder component which represented the most likely pin layout, so just use that diagram in conjunction with the notes and look at the photo of the rotary encoder to see what you are more likely to be looking for in terms of rotary encoder pin layout.

One of the two pins on one side of the rotary encoder (as opposed to the side with three pins) needs to be connected to ground and another to a digital pin on the Arduino. I have used D4 for the example sketch. If you choose a different pin, don't forget to change the value of buttonPin in the sketch.

Next comes the code in Step 2.

Step 2: Code

This is the code. By looking at the structure and the comments I hope you will find it easy to adapt for your specific needs!

/*******Interrupt-based Rotary Encoder Menu Sketch*******
 * by Simon Merrett, based on insight from Oleg Mazurov, Nick Gammon, rt and Steve Spence, and code from Nick Gammon
 * 3,638 bytes with debugging on UNO, 1,604 bytes without debugging
// Rotary encoder declarations
static int pinA = 2; // Our first hardware interrupt pin is digital pin 2
static int pinB = 3; // Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0; // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0; // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0; //somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent
// Button reading, including debounce without delay function declarations
const byte buttonPin = 4; // this is the Arduino pin we are connecting the push button to
byte oldButtonState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds
unsigned long buttonPressTime;  // when the switch last changed state
boolean buttonPressed = 0; // a flag variable
// Menu and submenu/setting declarations
byte Mode = 0;   // This is which menu mode we are in at any given time (top level or one of the submenus)
const byte modeMax = 3; // This is the number of submenus/settings you want
byte setting1 = 0;  // a variable which holds the value we set 
byte setting2 = 0;  // a variable which holds the value we set 
byte setting3 = 0;  // a variable which holds the value we set 
/* Note: you may wish to change settingN etc to int, float or boolean to suit your application. 
 Remember to change "void setAdmin(byte name,*BYTE* setting)" to match and probably add some 
 "modeMax"-type overflow code in the "if(Mode == N && buttonPressed)" section*/

void setup() {
  //Rotary encoder section of setup
  pinMode(pinA, INPUT_PULLUP); // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  pinMode(pinB, INPUT_PULLUP); // set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  attachInterrupt(0,PinA,RISING); // set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
  attachInterrupt(1,PinB,RISING); // set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
  // button section of setup
  pinMode (buttonPin, INPUT_PULLUP); // setup the button pin
  // DEBUGGING section of setup
  Serial.begin(9600);     // DEBUGGING: opens serial port, sets data rate to 9600 bps

void loop() {
  // carry out other loop code here 

void rotaryMenu() { //This handles the bulk of the menu functions without needing to install/include/compile a menu library
  //DEBUGGING: Rotary encoder update display if turned
  if(oldEncPos != encoderPos) { // DEBUGGING
    Serial.println(encoderPos);// DEBUGGING. Sometimes the serial monitor may show a value just outside modeMax due to this function. The menu shouldn't be affected.
    oldEncPos = encoderPos;// DEBUGGING
  // Button reading with non-delay() debounce - thank you Nick Gammon!
  byte buttonState = digitalRead (buttonPin); 
  if (buttonState != oldButtonState){
    if (millis () - buttonPressTime >= debounceTime){ // debounce
      buttonPressTime = millis ();  // when we closed the switch 
      oldButtonState =  buttonState;  // remember for next time 
      if (buttonState == LOW){
        Serial.println ("Button closed"); // DEBUGGING: print that button has been closed
        buttonPressed = 1;
      else {
        Serial.println ("Button opened"); // DEBUGGING: print that button has been opened
        buttonPressed = 0;  
    }  // end if debounce time up
  } // end of state change

  //Main menu section
  if (Mode == 0) {
    if (encoderPos > (modeMax+10)) encoderPos = modeMax; // check we haven't gone out of bounds below 0 and correct if we have
    else if (encoderPos > modeMax) encoderPos = 0; // check we haven't gone out of bounds above modeMax and correct if we have
    if (buttonPressed){ 
      Mode = encoderPos; // set the Mode to the current value of input if button has been pressed
      Serial.print("Mode selected: "); //DEBUGGING: print which mode has been selected
      Serial.println(Mode); //DEBUGGING: print which mode has been selected
      buttonPressed = 0; // reset the button status so one press results in one action
      if (Mode == 1) {
        Serial.println("Mode 1"); //DEBUGGING: print which mode has been selected
        encoderPos = setting1; // start adjusting Vout from last set point
      if (Mode == 2) {
        Serial.println("Mode 2"); //DEBUGGING: print which mode has been selected
        encoderPos = setting2; // start adjusting Imax from last set point
      if (Mode == 3) {
        Serial.println("Mode 3"); //DEBUGGING: print which mode has been selected
        encoderPos = setting3; // start adjusting Vmin from last set point
  if (Mode == 1 && buttonPressed) {
    setting1 = encoderPos; // record whatever value your encoder has been turned to, to setting 3
    //code to do other things with setting1 here, perhaps update display  
  if (Mode == 2 && buttonPressed) {
    setting2 = encoderPos; // record whatever value your encoder has been turned to, to setting 2
    //code to do other things with setting2 here, perhaps update display   
  if (Mode == 3 && buttonPressed){
    setting3 = encoderPos; // record whatever value your encoder has been turned to, to setting 3
    //code to do other things with setting3 here, perhaps update display 

// Carry out common activities each time a setting is changed
void setAdmin(byte name, byte setting){
  Serial.print("Setting "); //DEBUGGING
  Serial.print(name); //DEBUGGING
  Serial.print(" = "); //DEBUGGING
  encoderPos = 0; // reorientate the menu index - optional as we have overflow check code elsewhere
  buttonPressed = 0; // reset the button status so one press results in one action
  Mode = 0; // go back to top level of menu, now that we've set values
  Serial.println("Main Menu"); //DEBUGGING

//Rotary encoder interrupt service routine for one encoder pin
void PinA(){
  cli(); //stop interrupts happening before we read pin values
  reading = PIND & 0xC; // read all eight pin values then strip away all but pinA and pinB's values
  if(reading == B00001100 && aFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos --; //decrement the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  else if (reading == B00000100) bFlag = 1; //signal that we're expecting pinB to signal the transition to detent from free rotation
  sei(); //restart interrupts

//Rotary encoder interrupt service routine for the other encoder pin
void PinB(){
  cli(); //stop interrupts happening before we read pin values
  reading = PIND & 0xC; //read all eight pin values then strip away all but pinA and pinB's values
  if (reading == B00001100 && bFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos ++; //increment the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  else if (reading == B00001000) aFlag = 1; //signal that we're expecting pinA to signal the transition to detent from free rotation
  sei(); //restart interrupts
// end of sketch!

I have used "DEBUGGING" at the start of every comment on any line which isn't critical for the menu to do its thing. If you are happy with the menu's function, you might want to comment out or delete these lines for smaller compiled sketch size.

Be aware that a key part of menu navigation is feedback to the user while they are scrolling through the option and settings. Therefore if you choose not to include the DEBUGGING lines, you should probably use another visual indicator (e.g. LCD text display, LEDs) that encoder inputs are navigating the menu and changing settings.

If I comment out the DEBUGGING lines (noting that some visual feedback would still be needed for menu navigation) the compiled code is around 1,650 bytes for the Arduino Uno, hopefully leaving plenty of room on your ATMEGA328P for the more exciting parts of your sketch!

Go to Step 3 to find out how the menu system works.

Step 3: Operation and Conclusion


If you open the serial monitor in Arduino after uploading this sketch, and start to turn the encoder shaft, you should see the top level menu rotating through the number of sub-menus/options you have (limited using the modeMax variable). If you press the centre-push button you will see that the mode/sub-menu you have scrolled to is selected and now you have free reign to scroll through 0-255 values in that sub-menu. Now, if you press the centre-push button you will set that value to setting1 or setting2 or setting3 etc. The Arduino automatically and instantaneously returns you to the top level menu once this has happened.

While powered up, the Arduino remembers what you set each setting to and if you go back to the sub-menu for a setting you have already set a value to, it will start your encoder adjustments from the last value you chose!


I set out to write some sketch-based code that would allow rotary encoders to navigate a basic menu for Arduinos. I also tried to make it readable so that, unlike some alternatives, someone could see the menu structure and know what changes to the code they would need to make to tailor the menu to their needs.

This code is basic and generic, specifically to demonstrate the functionality while being easily adaptable to your own application. It uses the serial monitor as a basic debugging tool which also removes the need for a separate display if you want to see how the code works. I hope you find it useful and are inspired to edit, adapt and improve it!

Please share anything you do with it in the comments!

3 People Made This Project!


  • Plastics Contest

    Plastics Contest
  • Optics Contest

    Optics Contest
  • Audio Contest 2018

    Audio Contest 2018

71 Discussions


23 days ago

Good job SimonM83

I try encoder using only one IRQ, working same :


void PinA() //.................................................. // (PinA==0 && PinB==1) || (PinA==0 && PinB==1)

{ if (bitRead(PIND, 3) ^ bitRead(PIND, 2) ) // PIND==B000001000 || PIND==B0000000100

encoderPos --; //decrement the encoder's position count

else // reading==B00000000)

encoderPos ++; //increment the encoder's position count



Question 4 weeks ago

Hi Simon,

Thanks for sharing. I have never dealt with interrupts before, so this is my first attempt with them. I could use a little guidance from you or anyone on the thread. My situation is that I need to "long press" the button to enter the menu filed, then use the rotary to choose from a set value or decision. For more clarity the flow would look something like this:

Long press --> enters 1st menu

rotary to select --> On /Off

short press to save and move to menu 2

rotary to select number of minutes

short press to save and move to menu 3

rotary to select temperature

short press to save and move to menu 4

etc...until the last menu where it exist and returns to the main loop.

My current issue is that the interrupt pulls the arduino out of the menu loop and returns it back to the main loop. Hence I am unable to use the sequencing that you have in your code.





Question 6 weeks ago on Step 3

Hi Simon, I have seen this question asked a few times but fail to see the answer. I am very interested in using this code, and the 0-255 values suit my project on most places, but not all :)

How do I set, for instance, submenu 2 to a specific range. Let say that menu item 2 is length of a racetrack in miles. To prevent weird, unreal values, I would like to limit the input to a range between 3 and 10 miles. Can this be done, and if it can, would you mind sharing how I could do this? This would also help for 0/1 [yes/no] options too.

Thanks for your effort, it's appreciated.

2 more answers

Answer 6 weeks ago

Try the same modeMax approach in other modes as is used in Mode 0:

if (encoderPos > (modeMax+10)) encoderPos = modeMax; // check we haven't gone out of bounds below 0 and correct if we have
else if (encoderPos > modeMax) encoderPos = 0; // check we haven't gone out of bounds above modeMax and correct if we have

This should limit the values that encoderPos can adopt. You will need to create different variable names for your limit (such as modeMax0, modeMax1 etc.


Reply 6 weeks ago

Thanks - I have tried to get that working but without any luck. Do you have a working example by any chance?


7 weeks ago

Hi SimonM83

Thank you for sharing this piece of code. I have been playing with the rotary encoder for my final year project and I wanted a nice interface with it and not a keypad.


2 months ago on Step 2

Hi Simon. What a nice project you have done. This is a the best implementation so far which I tested. Working perfectly, I didn’t get any problems. Just I had modified your project for my usage on Teensy 3,2 and oled display 128/64 and I write some functions for specific ranges encoder to things in my code. Rangers like 0-127, -127,0,127, 0-1023
Button also I modified, now I have more functions on button like DoubleClick, Push/Hold/Release, Push/400ms and do something and so on.
Maybe if someone will be interesting and I get time, I will make Instructables about my implementations and improvements.
I had always lot of headache before I got pretty good implementation enc to my projects lot of libraries but no one good to usage straight away from the box. Now thanks to you my life will be easier , thank you.

4 replies

Reply 2 months ago

Thanks for letting me know this Instructable was useful to you - I owe much to people taking time to share knowledge online so it's good to know I'm giving back in a small way. I'm sure people would be interested in the teensy ported version, as well as some of your other features.


Reply 2 months ago

Hi Simon. Yeah I for sure share it. With proper done stuff, people can learn a lot and quickly. I’m too by writing/ rewriting reading codes, learn every day some new things. Just I wish for myself more time for activities because I’m pretty busy with number projects and work to do, but I will publish some my projects.


Reply 2 months ago

Hi would you share the code to set the ranges per menu please? Thanks!


Reply 2 months ago

Hi. Yeah I will make instructabbles and on GitHub too, I will share my implementation Simon’s encoder project and menu. I have almost done my code with real midi controller + neopixels and other valuable solutions. Give me please little bit time to finish work. It will be my first indictable hahah, parallel I prepare things and description for that. Coming time to sharing my music audio/midi projects and instructions how to making mods/repairs vintage analog synths and so on. Be patient, you will be happy.
My idea is to sharing functionality and full done projects, because by reading code and truly useful stuff testing, people can learn a lot.

Dylan Rhodes

Question 3 months ago on Step 3

Hello! First, you helped tremendously! This is awesome code and have been very helpful. I was just wondering if you can maybe give some input on how I might be able to adapt it to my application...

I am using a 24 indent rotary encoder, and 24 LED NeoPixel. I want the rotary encoder to line up with the pixel, so that where the arrow on the knob is pointing is what LED is being controlled in some way (this is easy enough as I can just have the knob in a set position when it starts and it will be lined up). I am using this for audio so I have two menus (for now). The main one for volume, and one for brightness. When everything boots up, my hope is that the volume can just be changed off the bat without having to change into a menu. To switch menus, like to the brightness one for example, I want to trigger it on a button press but only when the very bottom LED (LED 0 of 23) is "selected". That is the LED I have designated to be status and menus, as opposed to being used for things like setting the brightness or volume.

I think I have this part pretty much figured out, but because of the LED ring, I wanted to limit it to steps on the ring. For example, I would have set volume steps for positions 1-23, but going a full 360 and continuing will not do anything. Likewise with the brightness, I do not think that I need THAT much control where I would need to do every number 0-255, rather I would do some reasonable math to confine it to my range. I have modified the code so that when it increases from 23, it sets it to 0, and decreasing from 0 will set it to 23. That works as expected.

I am having trouble getting into the next menu. I have added Serial.println("Checkpoints") so I can see where it is and is not getting to in the code, and I cannot quite figure it out. Any thoughts or suggestions?

1 more answer
SimonM83Dylan Rhodes

Answer 3 months ago


//Main menu section

if (Mode == 0) {...

try changing:

if (buttonPressed){

Mode = encoderPos; //


if (buttonPressed && encoderPos == 0) { // this will only let the button change the mode if the encoder is at zero

Mode = (Mode+1) % 2 ; // this will alternate the mode between 0 and 1. Just increase 2to 3 to get three modes etc.

Otherwise you'll need to post your code before people can help much more.


6 months ago

Hi Simon, Awesome article, iv been strugaling with rotary encoders for ages and this really helped! I still have a problem tho (my coding ability is tiny)...

I'm trying to get the code to do a keyboard.press on a clockwise rotation, a different one on counter-clockwise and if possible (stretch goal) a third different keyboard.press on the button press.

I have found putting the keyboard.press / keyboard release lines in the void "rotarymenu" section after the

"if buttonstate ==low" argument (just under serial.println ("button closed"))

works for that keypress (a for example) in both directions of the dial, but I cant figure out how to get it so it it only does a for clockwise and a different key (b) for the opposit direction. Is it just a case of putting the kreypress in the right sections or will i need to write entirely new arguments?

1 reply

Reply 3 months ago

I would look in rotaryMenu() and in the conditional statement

if(oldEncPos != encoderPos) { // DEBUGGING

I would put further checks for which direction, such as:

if(oldEncPos > encoderPos) keyboard.press "a";

else keyboard.press "b";


then I would look in the "if buttonState == LOW" as you already have done to put the keyboard.press "c". Not sure why it's currently triggering when you press the button unless you are rotating the encoder as you press it.


Question 4 months ago

Hi Mr. Simon. How i can contact you please give me email address
Thanks regards

1 more answer

Answer 4 months ago

If it's a message you don't want to put in the comments, I think you can send me a private message using your Instructables account.


9 months ago

How would one go about adding a sub menu with settings in the submenu, Such as hours and minutes in a "set time" sub menu?
-set time
-set alarm

1 reply

Nevermind,.. I figured it out,. Created another variable called submode and just mirrored the structure of the mode selection, in submode selection for each mode.
Can post code if anyone needs it.