Arduino LCD cursor position navigation using keypad

Here is a simple method using Arduino and 4×4 keypad to navigate the LCD cursor position. This is useful for projects that require menu control, multiple inputs using a keypad, etc.

Refer LCD and keypad interface with Arduino.

Arduino LCD interface w/ or w/o I2C.

In the code, the cursor navigation will be enabled once the switch ‘A’ is pressed. Then the switches 2,6,8,4 function as up, right, down, left buttons for navigation as shown below.

Code operation

  1. To start navigation, Press switch A.
  2. Use navigation switches to move the cursor.
  3. Pressing B removes the character where the cursor is currently on.
  4. Press 5, it acts as an ok button that disables the navigation and fixes the cursor at this position.

Arduino code LCD cursor position navigation using 4×4 keypad 

#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {2, 3, 4, 5};
byte colPins[COLS] = {6, 7, 8, 9};
int i = 0, j = 0;
String navigation = "OFF";
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(j, i);
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    if (key == 'A') {
      navigation = "ON";
      lcd.setCursor(j, i);
      lcd.blink();
    } else if (navigation == "OFF") {
      //lcd.setCursor(j, i); Add if each letter need to display at the same column.
      lcd.print(key);
    } else if (navigation == "ON") {
      /*Functions of button 2,6,8,4,5,B when cursor navigation ON.
        2,6,8,4 for up,right,down,left respectively
        B - clear column character.
        5-ok button, turn cursor navigation off
      */
      switch (key) {
        // Up
        case '2' :
          i = 0;
          break;
        //Right
        case '6'  :
          if (j < 15) {
            j++;
          }
          break;
        //Down
        case '8'  :
          i = 1;
          break;
        // Left
        case '4'  :
          if (j >= 0) {
            j--;
          }
          break;
        //Turn off cursor navigation.
        case '5' :
          navigation = "OFF";
          //To stop cursor Blinking.
          lcd.noBlink();//Remove if cursor needs to keep blinking
          break;
        //Clear column character
        case 'B' :
          lcd.setCursor(j, i);
          lcd.print(" ");
          break;
      }
      lcd.setCursor(j, i);
    }
  }
}

Now on pressing any key other than ‘A’ the LCD starts to displays from the last cursor position. The switch B works as a normal letter when the navigation is disabled. Pressing ‘A’ again takes to navigation mode.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *