Display, Hide a LCD screen with button


I’m using a LCD and a UNO.
I have a simple problem i can’t solve with the following code.

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F,20,4);

static byte previousSelect;

void setup() {

  lcd.begin(20, 4);



void loop() {
  byte Select = digitalRead(5);
    lcd.print("Screen 1");
  if (Select != previousSelect and Select == HIGH) { 
  previousSelect = Select;



      lcd.print("Stats screen");

I manage to display a sub screen with the ‘DISPLAY_SCREEN()’ function but only with a delay();

Now i want to be able to close this sub screen with the ‘Select’ button instead of waiting the end of the delay(3000);

Could someone help me?

Sounds like a state machine would be useful.

Only execute the code for the current state

I'm sorry, i'm new, i don't understand what a 'state machine' means.
Also, can you be a little more explicit about how to 'execute the code for the current state'.

From my part i'm asking myself if i have to make a breakable loop into the function or if i must restructure the main program.

Sorry about the terse nature of the previous message but I was on my 'phone at the time.

A state machine is a “posh” name for a program that is in one of several states at any one time. In your case that would be either displaying the main screen or the sub screen. Two states.

Imagine that you have s variable named currentState the value of which can be 0 or 1. When it is 0 the main screen is displayed and the program tests for a button press. When the button press is detected change currentState to 1 and display the sub screen and detect a button press to change back to state 0.

You can use if for this as in this pseudo code

if (currentState == 0)
  //code here to display main screen and detect button press
  if (button becomes pressed)
      set currentState to 1
if (currentState == 1)
  //code here to display sub screen and detect button press
  if (button becomes pressed)
      set currentState to 0

Personally I favour using switch/case instead of if/else but you may be more familiar with the former