#define enc_pin  3
#define led_pin  5
#define det_pin  A0
#define Max_MainMenu 3

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

LiquidCrystal_I2C lcd(0x27,16,2); 

bool xBut;
int rDet;

void setup() {
  lcd.init();                     
  lcd.backlight();// Включаем подсветку дисплея
  pinMode(enc_pin, INPUT_PULLUP);
  pinMode(led_pin, OUTPUT);
}

void loop() {
  static byte count;
  xBut = !digitalRead(enc_pin);
  count = count_click(xBut,Max_MainMenu,1);
  rDet = analogRead(det_pin);

  switch (count){
    case 0:     //menu 1 main
    lcd.setCursor(0,0);
    lcd.print("MAIN");
    lcd.setCursor(0,1);
    lcd.print("REAL");
    lcd.setCursor(5,1);
    //lcd.print(count_click(xBut, 250, 25, but_held(xBut, 5000)));
    lcd.print(but_held(xBut, 3000));
      break;
    case 1:     //menu 2 sett
    lcd.setCursor(0,1);
    lcd.print(2);
      break;
    case 2:     //menu 3 sett
    lcd.setCursor(0,1);
    lcd.print(3);
      break;
  }

}


byte count_click(bool But,byte MaxMainMenu, byte step){
  static bool flag;
  static byte ret;

    if(But && flag == 0){
    ret += step;
    flag = 1;
    }
    if(But==0 && flag==1){
      flag = 0;
    }
  
  if(ret>=MaxMainMenu) ret = 0;
  return ret;
}

bool but_held(bool But, int timeHeld){
  static bool ret;
  static bool flagH;
  static unsigned long tmr;
  static bool flag;

  if(But && flag == 0){
    tmr = millis();
    flag = 1;
  }
  if(But==0 && flag==1){
      flag = 0;
  }

  if(But && flagH == 0 && millis()-tmr > timeHeld){
    ret = !ret;
    flagH = 1;
  }
  if(But == 0 && flagH) flagH = 0;
  return ret;
}