import machine, time

i2c=machine.I2C(0)


# this device has two I2C addresses
DISPLAY_RGB_ADDR = 0x62
DISPLAY_TEXT_ADDR = 0x3e

RGB_REG0=0x00
RGB_REG1=0x01
RGB_REG5=0x08
RGB_REGR=0x04
RGB_REGG=0x03
RGB_REGB=0x02

i2c=machine.I2C(0)

def reg_write(i2c,addr,reg,data):
    msg=bytearray()
    msg.append(data)
    i2c.writeto_mem(addr,reg,msg)

# set backlight to (R,G,B) (values from 0..255 for each)
def setRGB(r,g,b):
    reg_write(i2c,DISPLAY_RGB_ADDR,RGB_REG0,0) 
    reg_write(i2c,DISPLAY_RGB_ADDR,RGB_REG1,0)
    reg_write(i2c,DISPLAY_RGB_ADDR,RGB_REG5,0xaa) 
    reg_write(i2c,DISPLAY_RGB_ADDR,RGB_REGR,r)
    reg_write(i2c,DISPLAY_RGB_ADDR,RGB_REGG,g)
    reg_write(i2c,DISPLAY_RGB_ADDR,RGB_REGB,b)
    
def textCommand(cmd):
    reg_write(i2c,DISPLAY_TEXT_ADDR,0x80,cmd)
    
def setText(text):
    textCommand(0x01)
    time.sleep(.05)
    textCommand(0x08 | 0x04)
    textCommand(0x28)
    time.sleep(.05)
    count=0
    row=0
    for c in text:
        if c == '\n' or count == 16:
            count=0
            row+=1
            if row ==2:
                break
            textCommand(0xc0)
            if c == '\n':
                continue
        count +=1
        reg_write(i2c,DISPLAY_TEXT_ADDR,0x40,ord(c))
        
def setText_norefresh(text):
    textCommand(0x02) # return home
    time.sleep(.05)
    textCommand(0x08 | 0x04) # display on, no cursor
    textCommand(0x28) # 2 lines
    time.sleep(.05)
    count = 0
    row = 0
    while len(text) < 32: #clears the rest of the screen
        text += ' '
    for c in text:
        if c == '\n' or count == 16:
            count = 0
            row += 1
            if row == 2:
                break
            textCommand(0xc0)
            if c == '\n':
                continue
        count += 1
        reg_write(i2c,DISPLAY_TEXT_ADDR,0x40,ord(c))
        
def clearText():
    textCommand(0x01)