ARDUINO: Console menu with switch()

Let´s see the code that create easy menu for arduino in console. We will work with numbers 1-4 for avaiable options. When your input is not number, console will ignore that input, if it is number, but menu has not option, console reply with “!WRONG INPUT!” and you must insert new input value.

November 30th 2018

Basic setup for arduino:- variable for input, setup console & print menu:

int receivedInt; //prepare variable for input

void setup() {
Serial.begin(9600); //setup console

//Print main menu
Serial.println("<MAIN MENU>");
Serial.println("------------------------");
Serial.println("1.)OPTION 1");
Serial.println("2.)OPTION 2");
Serial.println("3.)OPTION 3");
Serial.println("4.)OPTION 4");
Serial.println("------------------------");
}

We are ready to code function´s for read input and print result to console. We will use loop function + create recvInt() and PrintByInput()

void loop() {
recvInt(); //call function to read value from console
PrintByInput(); //call function with SWITCH
}

Function named recvInt() wait for input. Input must be number (int), other characters will be ignored becouse of Serial.parseInt()

void recvInt() {
while(Serial.available() == 0) { } //wait for input from console
receivedInt = Serial.parseInt(); // parse input to INT, other values are ignored
}

After that we have our value in receivedInt variable, let´s do what we need – this is just menu, so print info is enough.

void PrintByInput() {
if (receivedInt != NULL) { //call SWITCH if input is available
switch (receivedInt) { //print by input, otheway say !WRONG INPUT!
case 1:
Serial.print("OPTION-");
Serial.println(receivedInt);
break;
case 2:
Serial.print("OPTION-");
Serial.println(receivedInt);
break;
case 3:
Serial.print("OPTION-");
Serial.println(receivedInt);
break;
case 4:
Serial.print("OPTION-");
Serial.println(receivedInt);
break;
default:
Serial.println("!WRONG INPUT!");
break;
}
receivedInt = NULL; //clear variable value
}
}

Download sketch
Arduino_menu_in_console.zip
November 30, 2018
768 B