add_library('serial')

s = ""
line_count = 0
MAX_LINES = 40

port = "/dev/ttyUSB0"
speed = 115200
ser = Serial(this, port, speed)

def setup():
    size(500, 500, P3D)

def delay(mils):
    lastTime = millis()
    while (millis() - lastTime) < mils:
        pass

def get_char():
    global ser
    msg = 0
    buffer = ""
    
    if ser.available():   
        msg = ser.read()
        buffer += chr(msg)
    delay(1)
    return buffer

def draw():
    background(0)
    fill(0)
    noStroke()
    
    global s
    # text(string, x, y)
    fill(255, 255, 255)
    text(s, 10, 12)

    c = get_char()
    
    s += c
    if c == '\n':
        global line_count
        line_count += 1  
        if line_count > MAX_LINES:
            line_count = 0
            s = ""
        
def keyPressed():
    global key
    global ser
    if key == '\r':
        key = chr(10)
    if key > chr(31):
        ser.write(key)