Interactive Arduino menu system over serial line

> Coding, hacking, computer graphics, game dev, and such...
User avatar
fips
Site Admin
Posts: 166
Joined: Wed Nov 12, 2008 9:49 pm
Location: Prague
Contact:

Interactive Arduino menu system over serial line

Post by fips »

There is a simple and convenient way to interact with an Arduino board via serial line using a terminal application, such as PuTTY, which supports ANSI escape codes. This makes it super easy to serve the user with an interactive menu like this one:

Image

The example below shows how to approach this:

Code: Select all

// [CODE BY FIPS @ 4FIPS.COM, (c) 2016 FILIP STOKLAS, MIT-LICENSED]

#define RST "\033[0m"
#define SEL "\033[1;93;41m"

static int sel = 0;

void refresh() {
    Serial.print("\033[2J"); // clear screen
    Serial.print("\033[H"); // cursor to home
    Serial.print(sel == 0 ? SEL : RST);
    Serial.println("   Menu Item 1   ");
    Serial.print(sel == 1 ? SEL : RST);
    Serial.println("   Menu Item 2   ");
    Serial.print(sel == 2 ? SEL : RST);
    Serial.println("   Menu Item 3   ");
    Serial.print(RST);
}

void setup() {
    Serial.begin(9600);
    while (!Serial) delay(100);
    refresh();
}

void loop() {
    if (Serial.available()) {
        switch (Serial.read()) {
            case '[': {
                sel = sel <= 0 ? 0 : (sel - 1);
                break;
            }
            case ']': {
                sel = sel >= 2 ? 2 : (sel + 1);
                break;
            }
        }
        refresh();
    }
}