Guides · 8 min read

Arduino LCD Menu: Rotary Encoder, Submenus and EEPROM Saving

Build an Arduino LCD menu: navigate with a rotary encoder or 3 buttons, add submenus, edit values, save to EEPROM. State machine, LcdMenu library and ESP32.

An Arduino LCD menu is the most practical way to give a device dozens of settings with just one screen and one knob: turn to move between lines, press to pick a value, turn to change it and press again to confirm. The front panels of 3D printers, bench power supplies and thermostats work exactly like this. In this guide you will write, from scratch, a menu for a 16x2 I2C LCD and a KY-040 rotary encoder that has submenus, edits values and keeps your settings even after a power cut.

First we design the menu tree on paper, then code it with a state machine and a table of items, so that adding a new setting becomes a one-line job. After that we drive the same menu with three buttons instead of the encoder, compare it with the ready-made LcdMenu library and move the code to an ESP32 without rewriting it.

16x2 LCD display with I2C backpack
16x2 LCD with an I2C backpack: 16 characters on each of two lines and only four wires. In a menu, the two lines show a window onto a longer list.

How does a menu work? Three states, four events

Every LCD menu is really a small state machine. Ours has three states: HOME (the status screen while the device runs), BROWSE (moving through a list) and EDIT (changing the selected value). Inputs boil down to four events: NEXT (turn right or the down button), PREV (turn left or the up button), CLICK (short press) and LONG_PRESS (hold for 0.7 seconds, meaning back). The menu code only talks to these events; it does not care whether they come from an encoder, buttons or the serial port. Thanks to this split, changing the input hardware means changing a single function.

The menu tree: design it on paper first

Our example device is a dimmable LED lamp: its brightness, mode (steady, blinking or slowly fading) and blink period are changed from the menu, while the backlight timeout lives in a submenu. Item labels are limited to 9 characters, because a 16-character line reserves 1 character for the cursor (>) and 6 for the value. In your own project the LED can be a relay, a motor or a heater; the menu structure stays the same.

LevelShown on the LCDTypeRange / stepPurpose
Home screenLED 70% SteadyStatus screen–Click to enter the menu
Main menuBright %Value0–100, 5LED brightness
Main menuModeChoiceSteady / Blink / FadeOperating mode
Main menuBlink msValue100–2000, 100Blink or fade period
Main menuSettingsSubmenu–Opens the settings submenu
Main menuSave+exitAction–Writes to EEPROM, returns home
SettingsBacklightValue0–60 s, 5 (0 = always on)Backlight timeout
SettingsReset allAction–Restores the defaults
Settings< BackBack–Returns to the main menu

Parts and wiring

ConnectionArduino UnoESP32
LCD GNDGNDGND
LCD VCC5VVIN (5V)
LCD SDAA4GPIO 21
LCD SCLA5GPIO 22
Encoder CLKD2 (interrupt)GPIO 25
Encoder DTD3 (interrupt)GPIO 26
Encoder SW (button)D4GPIO 27
Encoder +5V3V3
Encoder GNDGNDGND
LED (with 220 Ω resistor)D9 (PWM)GPIO 2
On the ESP32, always connect the encoder's + pin to 3V3; the KY-040's pull-up resistors go to that pin, so feeding it 5 V would put 5 V on the 3.3 V inputs through CLK and DT. The LCD's I2C backpack also pulls SDA and SCL up to 5 V; it usually works, but a level shifter is the safest option (details in the I2C LCD display guide). If the screen lights up but shows no text, turn the contrast trimmer on the back and try address 0x3F instead of 0x27.

Install Frank de Brabander's LiquidCrystal I2C library from the Library Manager; the encoder and EEPROM need no extra libraries. The code below is a single file that compiles on both the Arduino Uno and the ESP32; the pins at the top are picked automatically for the board you use.

C++ (Arduino IDE)
1// Arduino LCD menü: rotary encoder + alt menü + EEPROM / LCD menu: encoder + submenu + EEPROM
2#include <Wire.h>
3#include <LiquidCrystal_I2C.h>
4#include <EEPROM.h>
5
6#if defined(ESP32)
7  const int ENC_CLK = 25, ENC_DT = 26, ENC_SW = 27, LED_PIN = 2;
8  #define ISR_ATTR IRAM_ATTR
9#else
10  const int ENC_CLK = 2, ENC_DT = 3, ENC_SW = 4, LED_PIN = 9;   // Uno: kesme pinleri 2 ve 3 / interrupt pins 2 and 3
11  #define ISR_ATTR
12#endif
13
14LiquidCrystal_I2C lcd(0x27, 16, 2);    // adres 0x3F da olabilir / address may be 0x3F
15
16// Ayarlar: tek dizi, EEPROM'a tek seferde yazılır / settings: one array, saved in one go
17enum { BRIGHT, MODE, SPEED, LIGHT, NUM_SETTINGS };
18int16_t setting[NUM_SETTINGS];
19const int16_t DEFAULTS[NUM_SETTINGS] = {70, 0, 500, 30};
20const uint8_t EE_MAGIC = 0x42;           // yapı değişince değiştir / change when the layout changes
21const char* const MODES[] = {"Steady", "Blink", "Fade"};
22
23// Menü ağacı veri olarak / the menu tree as data
24enum Kind : uint8_t { VALUE, CHOICE, SUBMENU, ACTION, BACK };
25enum { ACT_SAVE, ACT_RESET };
26struct Item {
27  const char* label;
28  Kind kind;
29  int8_t ref;                            // ayar, alt menü ya da eylem no / setting, submenu or action
30  int16_t minV, maxV, step;
31};
32const Item MAIN_ITEMS[] = {
33  {"Bright %",  VALUE,   BRIGHT,   0,   100,  5},
34  {"Mode",      CHOICE,  MODE,     0,   2,    1},
35  {"Blink ms",  VALUE,   SPEED,    100, 2000, 100},
36  {"Settings",  SUBMENU, 1,        0,   0,    0},
37  {"Save+exit", ACTION,  ACT_SAVE, 0,   0,    0},
38};
39const Item SETTINGS_ITEMS[] = {
40  {"Backlight", VALUE,   LIGHT,     0, 60, 5},
41  {"Reset all", ACTION,  ACT_RESET, 0, 0,  0},
42  {"< Back",    BACK,    0,         0, 0,  0},
43};
44struct Menu { const Item* items; uint8_t count; int8_t parent; };
45const Menu MENUS[] = {
46  {MAIN_ITEMS,     sizeof(MAIN_ITEMS) / sizeof(Item),     -1},
47  {SETTINGS_ITEMS, sizeof(SETTINGS_ITEMS) / sizeof(Item), 0},
48};
49
50// Durum makinesi / state machine
51enum State { HOME, BROWSE, EDIT };
52State state = HOME;
53uint8_t menuId = 0, cursor = 0, top = 0;
54bool dirty = true;                       // ekran yenilensin mi / redraw needed
55unsigned long lastActivity = 0;
56bool lightOn = true;
57
58// Giriş katmanı / input layer
59enum Event { NONE, NEXT, PREV, CLICK, LONG_PRESS };
60volatile int8_t encSteps = 0;
61
62void ISR_ATTR encoderISR() {
63  static uint8_t last = 3;
64  static int8_t acc = 0;
65  static const int8_t TABLE[16] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
66  uint8_t now = (digitalRead(ENC_CLK) << 1) | digitalRead(ENC_DT);
67  acc += TABLE[(last << 2) | now];
68  last = now;
69  if (now == 3) {                        // tık noktası: iki pin HIGH / detent: both pins HIGH
70    if (acc >= 2) encSteps++;
71    else if (acc <= -2) encSteps--;
72    acc = 0;
73  }
74}
75
76Event readButton() {
77  static bool stable = HIGH, lastRead = HIGH, longSent = false;
78  static unsigned long changedAt = 0, pressedAt = 0;
79  bool r = digitalRead(ENC_SW);
80  if (r != lastRead) { lastRead = r; changedAt = millis(); }
81  if (millis() - changedAt > 25 && r != stable) {   // 25 ms debounce
82    stable = r;
83    if (r == LOW) { pressedAt = millis(); longSent = false; }
84    else if (!longSent) return CLICK;                 // bırakınca kısa basış / short press on release
85  }
86  if (stable == LOW && !longSent && millis() - pressedAt > 700) {
87    longSent = true;
88    return LONG_PRESS;                                // 0,7 sn basılı tut = geri / hold 0.7 s = back
89  }
90  return NONE;
91}
92
93Event readInput() {
94  noInterrupts();
95  int8_t s = encSteps;
96  if (s > 0) encSteps--;
97  else if (s < 0) encSteps++;
98  interrupts();
99  if (s > 0) return NEXT;
100  if (s < 0) return PREV;
101  return readButton();
102}
103
104// EEPROM
105void loadSettings() {
106#if defined(ESP32)
107  EEPROM.begin(64);                      // ESP32'de flash öykünmesi / flash emulation on ESP32
108#endif
109  if (EEPROM.read(0) == EE_MAGIC) EEPROM.get(1, setting);
110  else memcpy(setting, DEFAULTS, sizeof(setting));
111  for (const Menu& m : MENUS) {                          // aralık dışını düzelt / fix out-of-range data
112    for (uint8_t i = 0; i < m.count; i++) {
113      const Item& it = m.items[i];
114      if (it.kind != VALUE && it.kind != CHOICE) continue;
115      if (setting[it.ref] < it.minV || setting[it.ref] > it.maxV) setting[it.ref] = DEFAULTS[it.ref];
116    }
117  }
118}
119
120void saveSettings() {
121  if (EEPROM.read(0) != EE_MAGIC) EEPROM.write(0, EE_MAGIC);
122  EEPROM.put(1, setting);                // AVR'de yalnız değişen baytları yazar / AVR writes changed bytes only
123#if defined(ESP32)
124  EEPROM.commit();
125#endif
126}
127
128// Ekran / display
129void printRow(uint8_t row, const char* text) {
130  char buf[17];
131  snprintf(buf, sizeof(buf), "%-16s", text);  // boşlukla doldur, titreme yok / pad, no flicker
132  lcd.setCursor(0, row);
133  lcd.print(buf);
134}
135
136void valueText(const Item& it, char* out, size_t n) {
137  if (it.kind == CHOICE) snprintf(out, n, "%s", MODES[setting[it.ref]]);
138  else if (it.kind == VALUE) snprintf(out, n, "%d", setting[it.ref]);
139  else if (it.kind == SUBMENU) snprintf(out, n, ">");
140  else out[0] = '\0';
141}
142
143void draw() {
144  char line[17], val[8];
145  if (state == HOME) {
146    snprintf(line, sizeof(line), "LED %3d%% %s", setting[BRIGHT], MODES[setting[MODE]]);
147    printRow(0, line);
148    printRow(1, "Click = menu");
149    return;
150  }
151  const Menu& m = MENUS[menuId];
152  if (state == EDIT) {
153    const Item& it = m.items[cursor];
154    valueText(it, val, sizeof(val));
155    printRow(0, it.label);
156    snprintf(line, sizeof(line), "  < %s >", val);
157    printRow(1, line);
158    return;
159  }
160  for (uint8_t row = 0; row < 2; row++) {      // BROWSE: iki satırlık pencere / two-row window
161    uint8_t i = top + row;
162    if (i >= m.count) { printRow(row, ""); continue; }
163    valueText(m.items[i], val, sizeof(val));
164    snprintf(line, sizeof(line), "%c%-9.9s%6s", i == cursor ? '>' : ' ', m.items[i].label, val);
165    printRow(row, line);
166  }
167}
168
169// Menü mantığı / menu logic
170void goBack() {
171  int8_t parent = MENUS[menuId].parent;
172  if (parent < 0) { state = HOME; return; }
173  const Menu& p = MENUS[parent];
174  for (uint8_t i = 0; i < p.count; i++) {      // imleci alt menü satırına koy / cursor on the submenu row
175    if (p.items[i].kind == SUBMENU && p.items[i].ref == (int8_t)menuId) cursor = i;
176  }
177  menuId = parent;
178  top = cursor > 0 ? cursor - 1 : 0;
179}
180
181void select(const Item& it) {
182  switch (it.kind) {
183    case VALUE:
184    case CHOICE:  state = EDIT; break;
185    case SUBMENU: menuId = it.ref; cursor = 0; top = 0; break;
186    case BACK:    goBack(); break;
187    case ACTION:
188      if (it.ref == ACT_SAVE) { saveSettings(); state = HOME; }
189      else memcpy(setting, DEFAULTS, sizeof(setting));
190      break;
191  }
192}
193
194void handle(Event e) {
195  if (e == NONE) return;
196  lastActivity = millis();
197  if (!lightOn) { lcd.backlight(); lightOn = true; }
198  dirty = true;
199  const Menu& m = MENUS[menuId];
200  const Item& it = m.items[cursor];
201  switch (state) {
202    case HOME:
203      if (e == CLICK) { state = BROWSE; menuId = 0; cursor = 0; top = 0; }
204      break;
205    case BROWSE:
206      if (e == NEXT && cursor + 1 < m.count) cursor++;
207      else if (e == PREV && cursor > 0) cursor--;
208      else if (e == CLICK) select(it);
209      else if (e == LONG_PRESS) goBack();
210      if (cursor < top) top = cursor;
211      if (cursor > top + 1) top = cursor - 1;
212      break;
213    case EDIT:
214      if (e == NEXT || e == PREV) {
215        int16_t v = setting[it.ref] + (e == NEXT ? it.step : -it.step);
216        if (it.kind == CHOICE) {               // seçenekler döner / choices wrap around
217          if (v > it.maxV) v = it.minV;
218          if (v < it.minV) v = it.maxV;
219        }
220        setting[it.ref] = constrain(v, it.minV, it.maxV);
221      } else {
222        state = BROWSE;                        // tık ya da uzun basış onaylar / click or hold confirms
223      }
224      break;
225  }
226}
227
228// Uygulama: LED çıkışı / application: LED output
229void runLed() {
230  int pwm = map(setting[BRIGHT], 0, 100, 0, 255);
231  unsigned long t = millis();
232  unsigned long period = setting[SPEED];
233  if (setting[MODE] == 0) analogWrite(LED_PIN, pwm);
234  else if (setting[MODE] == 1) analogWrite(LED_PIN, (t / period) % 2 ? pwm : 0);
235  else {
236    unsigned long p = t % (2 * period);                   // üçgen dalga / triangle wave
237    unsigned long level = p < period ? p : 2 * period - p;
238    analogWrite(LED_PIN, pwm * level / period);
239  }
240}
241
242void setup() {
243  pinMode(ENC_CLK, INPUT_PULLUP);
244  pinMode(ENC_DT, INPUT_PULLUP);
245  pinMode(ENC_SW, INPUT_PULLUP);
246  pinMode(LED_PIN, OUTPUT);
247  attachInterrupt(digitalPinToInterrupt(ENC_CLK), encoderISR, CHANGE);
248  attachInterrupt(digitalPinToInterrupt(ENC_DT), encoderISR, CHANGE);
249  lcd.init();
250  lcd.backlight();
251  loadSettings();
252}
253
254void loop() {
255  handle(readInput());
256  if (dirty) { draw(); dirty = false; }
257  unsigned long idle = millis() - lastActivity;
258  if (state != HOME && idle > 30000) { state = HOME; dirty = true; }   // 30 sn sonra ana ekran / home after 30 s
259  if (lightOn && setting[LIGHT] > 0 && idle > setting[LIGHT] * 1000UL) {   // arka ışığı kapat / backlight off
260    lcd.noBacklight();
261    lightOn = false;
262  }
263  runLed();
264}

How the code works

Code partWhat it does
Item and MENUS arraysHold the menu tree as data: label, type, linked setting, minimum, maximum and step
setting[] and DEFAULTS[]All settings live in one array, written to and read from EEPROM in one go
encoderISR()Runs on every edge of CLK and DT, filters bounce with a state table and counts one step only at the detent
readButton()25 ms debounce for SW; a short press gives CLICK on release, holding for 0.7 s gives LONG_PRESS
readInput()Turns encoder steps and the button into NEXT, PREV, CLICK and LONG_PRESS; this is the only place the input hardware lives
handle()The state machine: decides what each event does in the HOME, BROWSE and EDIT states
select() and goBack()Enter a submenu, run an action, or go up one level and put the cursor back on the row you came from
draw() and printRow()Redraw only when something changed; rows are padded to 16 characters with spaces, so the screen does not flicker
loadSettings() / saveSettings()A marker byte tells whether the EEPROM data is valid; out-of-range values are fixed
runLed()The real application: drives the LED steady, blinking or fading from the settings, and keeps running while the menu is open

The biggest win of this structure is how easy the menu is to grow. To add a contrast setting to the main menu, you add a CONTRAST name to the settings list, a default to the DEFAULTS array and the row {"Contrast", VALUE, CONTRAST, 0, 10, 1} to MAIN_ITEMS; drawing, navigation, limits and EEPROM saving just work. A new submenu is an item array added to the MENUS list plus a SUBMENU row in its parent. To see in detail why the interrupt-driven encoder code never misses a click, read the rotary encoder guide.

Clearing the screen with lcd.clear() on every change is the most common cause of flicker: rewriting 32 characters over I2C takes tens of milliseconds and the screen looks blank in between. Padding the rows with spaces and writing over them, and only drawing when something changed, as in this code, removes the flicker and leaves more time for the encoder.

Editing values and saving to EEPROM

In the EDIT state each click changes the value by the item's step, and constrain() keeps it inside the limits; choice items wrap around at the end. The LED shows the change immediately, so the user sees the result before saving. Permanent saving only happens on Save+exit, because each cell of the Uno's 1024-byte EEPROM is rated for about 100,000 writes; writing on every click could wear out a heavily used device in months instead of years. On AVR, EEPROM.put() only writes the bytes that changed, which stretches the lifetime further.

EEPROM addressContentSize
0Marker byte (0x42): is the data valid?1 byte
1–2Bright % (int16_t)2 bytes
3–4Mode2 bytes
5–6Blink ms2 bytes
7–8Backlight2 bytes

A fresh Arduino's EEPROM is full of 0xFF, which is why the marker byte matters: if 0x42 is not found at start-up, the code uses the defaults. Whenever you add a field to the settings array or change its order, change EE_MAGIC as well (for example to 0x43), so data saved in the old layout is not read into the wrong fields. The code also checks every loaded value against the limits defined in the menu, so even a corrupted byte cannot lock up the menu.

No encoder? Three push buttons are enough: UP on D5, DOWN on D6 and OK on D7, with the other leg of each button to GND; the internal pull-ups mean no resistors are needed. Replace readInput() in the main code with the version below, delete the two attachInterrupt lines in setup() and put the three buttons' pinMode(..., INPUT_PULLUP) lines in their place. The rest of the menu stays untouched.

Four-leg tactile push button
Four-leg tactile button: opposite pairs of legs are connected inside, so place the button across the gap in the middle of the breadboard.
C++ (Arduino IDE)
1// 3 butonlu giriş: encoder yerine / three-button input instead of the encoder
2// Butonlar pin ile GND arasına, pinMode(..., INPUT_PULLUP) / buttons between pin and GND
3const uint8_t BTN_UP = 5, BTN_DOWN = 6, BTN_OK = 7;
4
5Event readInput() {
6  static const uint8_t pins[3] = {BTN_UP, BTN_DOWN, BTN_OK};
7  static bool stable[3] = {HIGH, HIGH, HIGH}, longSent = false;
8  static unsigned long changedAt[3], pressedAt[3], repeatAt[3];
9  Event up = state == EDIT ? NEXT : PREV;      // düzenlerken yukarı = artır / while editing, up = increase
10  Event down = state == EDIT ? PREV : NEXT;
11  unsigned long now = millis();
12  for (uint8_t i = 0; i < 3; i++) {
13    bool r = digitalRead(pins[i]);
14    if (r != stable[i] && now - changedAt[i] > 25) {   // 25 ms içindeki sıçramaları yok say / ignore bounce
15      stable[i] = r;
16      changedAt[i] = now;
17      if (r == LOW) {
18        pressedAt[i] = repeatAt[i] = now;
19        if (i == 0) return up;
20        if (i == 1) return down;
21        longSent = false;
22      } else if (i == 2 && !longSent) {
23        return CLICK;                                // OK bırakıldı / OK released
24      }
25    }
26    if (stable[i] == LOW) {
27      if (i < 2 && now - pressedAt[i] > 500 && now - repeatAt[i] > 120) {
28        repeatAt[i] = now;                           // basılı tutunca hızlı tekrar / auto-repeat when held
29        return i == 0 ? up : down;
30      }
31      if (i == 2 && !longSent && now - pressedAt[i] > 700) {
32        longSent = true;
33        return LONG_PRESS;                           // OK basılı = geri / hold OK = back
34      }
35    }
36  }
37  return NONE;
38}

This function does three jobs. It fires the event on the very first contact and ignores bounces for the next 25 ms, so the button responds without delay. If UP or DOWN is held for more than 0.5 seconds, it repeats the event every 120 ms, so you can sweep a value from 100 to 2000 without pressing a hundred times. Third, in edit mode it maps UP to NEXT: in a list, up moves to the previous row, but while editing a value, up should increase it. Holding OK for 0.7 seconds goes back, just like on the encoder.

The ready-made option: the LcdMenu library

If you would rather use a ready-made library than write the menu yourself, install LcdMenu (by Forntoh Thomas, version 5.x) and SimpleRotary for the encoder from the Library Manager. LcdMenu has you define the menu with the MENU_SCREEN macro; number ranges, on/off toggles, lists, submenus and commands come as ready item types. The example below is a trimmed-down version of the menu above.

C++ (Arduino IDE)
1// LcdMenu 5.x + SimpleRotary ile hazır menü / ready-made menu with LcdMenu 5.x + SimpleRotary
2#include <EEPROM.h>
3#include <ItemBack.h>
4#include <ItemCommand.h>
5#include <ItemRange.h>
6#include <ItemSubMenu.h>
7#include <ItemToggle.h>
8#include <LcdMenu.h>
9#include <MenuScreen.h>
10#include <SimpleRotary.h>
11#include <display/LiquidCrystal_I2CAdapter.h>
12#include <input/SimpleRotaryAdapter.h>
13#include <renderer/CharacterDisplayRenderer.h>
14
15#if defined(ESP32)
16  const int LED_PIN = 2, ENC_CLK = 25, ENC_DT = 26, ENC_SW = 27;
17#else
18  const int LED_PIN = 9, ENC_CLK = 2, ENC_DT = 3, ENC_SW = 4;
19#endif
20
21int brightness = 70;               // menü bu değişkeni doğrudan değiştirir / the menu edits it directly
22int blinkMs = 500;
23
24void onBrightness(const Ref<int> v) { analogWrite(LED_PIN, map(v.value, 0, 100, 0, 255)); }
25void toggleBacklight(bool on);
26void saveAll();
27
28extern MenuScreen* settingsScreen;
29
30MENU_SCREEN(mainScreen, mainItems,
31    ITEM_RANGE_REF<int>("Bright", brightness, 5, 0, 100, onBrightness, "%d%%"),
32    ITEM_RANGE_REF<int>("Blink", blinkMs, 100, 100, 2000, nullptr, "%dms"),
33    ITEM_SUBMENU("Settings", settingsScreen),
34    ITEM_COMMAND("Save", saveAll));
35
36MENU_SCREEN(settingsScreen, settingsItems,
37    ITEM_TOGGLE("Backlight", true, toggleBacklight),   // açık başlar / starts ON
38    ITEM_BACK());
39
40LiquidCrystal_I2C lcd(0x27, 16, 2);
41LiquidCrystal_I2CAdapter lcdAdapter(&lcd);
42CharacterDisplayRenderer renderer(&lcdAdapter, 16, 2);
43LcdMenu menu(renderer);
44SimpleRotary encoder(ENC_CLK, ENC_DT, ENC_SW);
45SimpleRotaryAdapter rotaryInput(&menu, &encoder);   // kısa bas = gir, uzun bas = geri / short = enter, long = back
46
47void toggleBacklight(bool on) { lcdAdapter.setBacklight(on); }
48
49void saveAll() {
50  EEPROM.put(0, brightness);
51  EEPROM.put(sizeof(int), blinkMs);
52#if defined(ESP32)
53  EEPROM.commit();
54#endif
55}
56
57void setup() {
58  pinMode(LED_PIN, OUTPUT);
59#if defined(ESP32)
60  EEPROM.begin(16);
61#endif
62  int b, s;
63  EEPROM.get(0, b);
64  EEPROM.get(sizeof(int), s);
65  if (b >= 0 && b <= 100) brightness = b;            // ilk açılışta EEPROM boş (-1) / EEPROM empty (-1) at first boot
66  if (s >= 100 && s <= 2000) blinkMs = s;
67  renderer.begin();
68  menu.setScreen(mainScreen);
69  analogWrite(LED_PIN, map(brightness, 0, 100, 0, 255));
70}
71
72void loop() {
73  rotaryInput.observe();
74}

ITEM_RANGE_REF edits the variable you pass in directly, so saving needs no extra read. ITEM_SUBMENU opens a child screen, ITEM_BACK returns, ITEM_COMMAND runs a function when selected and ITEM_TOGGLE flips ON/OFF. SimpleRotaryAdapter turns a short press into enter, a long press into back and a double press into backspace. Convenience has a price: on an Uno this example uses about 68% of flash and 62% of RAM, while our own menu code above does much more with 25% flash and 27% RAM.

On boards without a standard C++ library, such as the Uno, LcdMenu also needs the ArduinoSTL library. Building ArduinoSTL 1.3.3 with a recent AVR core can fail with the linker error multiple definition of std::nothrow. Fix: open Arduino/libraries/ArduinoSTL/src/new_handler.cpp and delete the line const std::nothrow_t std::nothrow = { }; or comment it out with //. The ESP32 does not have this problem; the library compiles as is.
CriterionYour own code (state machine)LcdMenu
Flash / RAM on an Uno25% / 27% (the full menu in this guide)68% / 62% (trimmed example)
Extra librariesOnly LiquidCrystal I2CLcdMenu, SimpleRotary, ArduinoSTL on the Uno
Screen layoutFully under your controlThe library's rendering style
Ready item typesYou add them (value, choice, submenu, action)Range, list, toggle, text input, command
LearningTeaches the state machine, you know every lineQuick start, you follow the library's rules
Best fitUno and Nano, low-memory projectsBoards with lots of memory like the ESP32, quick prototypes

The same menu on an ESP32

The main menu code compiles on the ESP32 without any changes; the differences hide in the #if defined(ESP32) blocks. The pins become GPIO 25, 26, 27 and 2, the interrupt handler is placed in fast memory with IRAM_ATTR, and because the EEPROM is an emulation on top of flash, it is opened with EEPROM.begin(64) and written with EEPROM.commit() after each save. analogWrite() works on both the 2.x and 3.x versions of the ESP32 core, so the LED code stays the same. A cleaner path on the ESP32 is the Preferences library, which uses the chip's NVS area instead of EEPROM; just swap the EEPROM functions in the main code for the two functions below.

C++ (Arduino IDE)
1// ESP32: EEPROM yerine Preferences (NVS) / Preferences (NVS) instead of EEPROM
2#include <Preferences.h>
3Preferences prefs;
4
5void loadSettings() {
6  prefs.begin("menu", true);                              // salt okunur / read-only
7  size_t n = prefs.getBytes("set", setting, sizeof(setting));
8  prefs.end();
9  if (n != sizeof(setting)) memcpy(setting, DEFAULTS, sizeof(setting));   // ilk açılış / first boot
10}
11
12void saveSettings() {
13  prefs.begin("menu", false);
14  prefs.putBytes("set", setting, sizeof(setting));        // NVS aşınmayı kendisi dağıtır / NVS spreads wear itself
15  prefs.end();
16}

Preferences stores settings under a key name and spreads the writes across flash on its own; it does not even need the marker byte, because if the key is missing or the size does not match, getBytes() returns a different length and the code falls back to the defaults. With the ESP32's ample memory, adding long lists such as Wi-Fi network selection, time zone or sensor calibration to the menu is no problem either.

Project ideas with an LCD menu

  • Thermostat: set the target temperature and hysteresis in the menu, measure with a DS18B20 and switch a heater with a relay.
  • Watering timer: keep the watering time, duration and soil moisture threshold in the menu; add an RTC module for the clock.
  • Stepper control panel: set speed, acceleration and step count with the encoder to drive a camera slider or a turntable.
  • Game menu: build a small LCD game with difficulty level, sound on/off and a high-score screen.
  • Safe settings: add a menu to change the code entered on a keypad and the lockout time.
  • Lab timer: set minutes and seconds with the encoder and sound a buzzer when time is up.

Common problems and fixes

SymptomLikely causeFix
Compile error: 'class LiquidCrystal_I2C' has no member named 'init'Two LCD libraries with the same name are installed and the wrong one is pickedKeep Frank de Brabander's LiquidCrystal I2C and remove the other one from the libraries folder
The cursor jumps two rows per clickThe encoder makes two full cycles per detent or the contacts bounceRaise the threshold in the ISR or halve the steps, add 10–100 nF capacitors on CLK and DT
It moves only every second clickHalf-cycle encoder (two transitions per detent)In the ISR, decide on now == 0 as well as now == 3
Direction is reversedCLK and DT are swappedSwap the ENC_CLK and ENC_DT pin numbers in the code
The screen flickerslcd.clear() on every loop or needless redrawsDraw only on changes, pad the rows with spaces
Settings are lost after a power cycleSave+exit was not used, or commit() is missing on the ESP32Use the save action; on the ESP32 use EEPROM.commit() or Preferences
Garbage values at start-upThe EEPROM holds data saved with an older layoutChange EE_MAGIC and the code falls back to defaults

A good LCD menu turns your project from an experiment tied to a computer into a real device: the settings live in the user's hands, not in the code. Sketch the menu tree on paper first, set up the state machine, then add the items one line at a time. In the BlueGrays app you will find projects such as I2C LCD basics, an LCD password lock, a calculator and an LCD runner game with circuit diagrams and ready code, and you can easily add this menu on top of them.

Frequently asked questions

How do I make a menu on a 16x2 LCD with Arduino?

Build it as a state machine: three states, home screen, browsing the list and editing a value, are enough. Keep the menu items in an array with their label, type and limits, and turn encoder or button input into events like NEXT, PREV and CLICK. Draw a two-line window onto the list only when something changes.

What is the best library for an Arduino LCD menu?

For a ready-made solution, LcdMenu is current, well documented and supports encoders, buttons and keyboard input; LCDMenuLib2 and ArduinoMenu are popular too. These libraries fill an Uno's 2 KB of RAM quickly, though. On small boards a hand-written state machine like the one in this guide uses far less memory.

How do I keep menu settings after a power cut?

Write the settings to EEPROM and read them back at start-up. Use a marker byte to check that the data is valid, compare the loaded values with the menu limits, and since EEPROM has limited write endurance, write only when the user chooses save, not on every click. On the ESP32 use EEPROM.commit() or the Preferences library.

Can I build an LCD menu with buttons instead of a rotary encoder?

Yes, three buttons, up, down and OK, are enough. Wire them with INPUT_PULLUP, debounce them in software and add auto-repeat so holding a button changes the value quickly. Because the menu code works with events, you only need to replace the input function.

Why does my LCD flicker when the menu updates?

The most common reason is calling lcd.clear() on every update: rewriting 32 characters over I2C takes tens of milliseconds and the screen looks blank meanwhile. Pad each row to 16 characters with spaces, write over it, and only redraw when a value or the cursor changes; the flicker goes away.

How many menu items fit on an Arduino Uno?

RAM is usually the limit. In the structure from this guide each item takes only a few bytes, but the label strings are copied into RAM too; for hundreds of items, move the strings to PROGMEM and read them from flash. Our menu code as it stands uses about 27% of the Uno's RAM, so there is plenty of room for dozens of items.

See all projects
Using LCD Screen with I2C
AR-32Beginner
Premium

Using LCD Screen with I2C

Give your Arduino its own screen and make it write its first message. The two-line LCD screen hooks up with just a few wires; a greeting appears on the top line, then a second message on the bottom…

4.8(53)
70
Print Message on 2x16 LCD Screen
AR-29Advanced
Premium

Print Message on 2x16 LCD Screen

Your first step to writing text on a screen. The two-line LCD screen first shows a waiting message, then writes a greeting on the top line and types a word letter by letter on the bottom line like a…

4.6(37)
51
ESP32 I2C LCD Display (16x2)
ES-17Intermediate
Premium

ESP32 I2C LCD Display (16x2)

In this project we connect a 16x2 character LCD to the ESP32 over I2C and display text. With I2C, just 2 data pins (SDA and SCL) control the screen, instead of the 6+ pins a classic parallel connection wastes. The code prints a fixed message on the first line and a counter that goes up every second on the second. At startup an I2C scanner also prints the display's address to the Serial Monitor (usually 0x27 or 0x3F).

4.9(23)
40
Password Lock with 4x4 Keypad and LCD
AR-64Advanced
Premium

Password Lock with 4x4 Keypad and LCD

A small electronic door lock that keeps out anyone who doesn't know the code. You press the hash key and type the code on the keypad; if it is right, the screen says access granted, the green LED…

4.8(59)
75
Arduino I2C Calculator
AR-94Intermediate
Premium

Arduino I2C Calculator

It is an Arduino-based calculator project that performs addition, subtraction, multiplication and division operations using a 4x4 membrane keypad and a 16x2 I2C LCD display. Thanks to I2C, the display connection is provided with only 2 cables, thus reducing cable clutter and keeping more pins open for use. There is also decimal number input and negative number support.

5.0(31)
43
Arduino LCD Runner Game
AR-96Intermediate
Premium

Arduino LCD Runner Game

Side scrolling endless runner game running on 16x2 character LCD screen. Hero runs automatically, player jumps over obstacles by pressing the button. Random obstacles appear on the top and bottom row. Passive buzzer plays opening melody, jumping sound, 50 point celebration sound and end of game melody. "BlueGrays - Arduino Projects" splash screen is shown on startup. The score is updated instantly in the upper right corner of the screen.

4.6(32)
56
DS1302 RTC Clock with LCD Display
AR-46Intermediate
Premium

DS1302 RTC Clock with LCD Display

A little desk clock that keeps the time even when the power goes out. The DS1302 clock module keeps time thanks to its own tiny battery; every second the Arduino reads it and writes the time and date…

4.7(41)
51
Temperature Measurement with NTC and 2x16 Lcd Display
AR-44Beginner
Premium

Temperature Measurement with NTC and 2x16 Lcd Display

Measure the temperature around you with a sensor that looks like a tiny bead. This part, called an NTC, lets electricity through more easily as it warms up; the Arduino reads that change, turns it…

4.5(33)
44