# MicroPython + ESP 32 + I2C-LCD-2x16-Modul Teil 2
import machine, time
from machine import Pin, SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd

def reset_display(lcd, title="Hauptmenu"):
    lcd.clear()
    lcd.putstr(title)

def laufzeit(lcd, up):
    reset_display(lcd, "Laufzeit")
    while True:
        lcd.move_to(0, 1)
        uhrzeit = "| {0:02d}:{1:02d}:{2:02d} |".format(time.localtime()[3],time.localtime()[4],time.localtime()[5])
        lcd.putstr(uhrzeit)
        if up.value() == 0:    
            reset_display(lcd)
            break

def stoppuhr(lcd, up, down, select):
    reset_display(lcd, "Stoppuhr")
    start = time.time()
    while True:
        lcd.move_to(0, 1)
        timer = time.time() - start
        lcd.putstr(str(timer) + " Sekunden")
        if up.value() == 0:    
            reset_display(lcd)
            break

def counter(lcd, up, select):
    reset_display(lcd, "Counter")
    counter = 0
    while True:
        lcd.move_to(0, 1)
        lcd.putstr(str(counter))
        if select.value() == 0:
            counter += 1
        if up.value() == 0:    
            reset_display(lcd)
            break

I2C_ADDR = 0x27
totalRows = 2       # zwei Zeilen
totalColumns = 16   # 16 Zeichen je Zeile
SDA_Pin = 21     # D21 -  gelb  - SDA
SCL_Pin = 22     # D22 - orange - SCL
select = Pin(15)
up  = Pin( 2)
down   = Pin( 4)
i2c = SoftI2C(scl=Pin(SCL_Pin), sda=Pin(SDA_Pin), freq=10000) 
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.display_on()
lcd.backlight_on()
lcd.putstr("Hauptmenu")
wahl = 0
i=0
while True:
    if wahl==0:
        lcd.move_to(0,1)    # Zeichen 0, Zeile 2
        lcd.putstr("               ")       
        lcd.move_to(0,1)    # Zeichen 0, Zeile 2
        if i==0:
            lcd.putstr("1 Laufzeit")
        else:
            if i==1:
                lcd.putstr("2 Stoppuhr")
            else:
                lcd.putstr("3 Counter")
        time.sleep(0.25)
    if select.value()==0:
        if i==0:
            laufzeit(lcd, up)
        elif i==1:
            stoppuhr(lcd, up, down, select)
        else:
            counter(lcd, up, select)
    i=(i + 1)%3