import serial
#imports serial library

#=======opening ports============#
#following code ensures user doesn't try to open port that doesn't exist
#by asking for correct port number every time port can not be opened
#note this also returns requests new port if port is already busy
ser = False
while(not ser):
    ser = input("please enter port number:\t")
    try:
        ser = serial.Serial(int(ser)-1)
	#stores serial port class reference in variable
    except:
        ser = False
        print("you entered invalid port number\nplease enter corract port number(usually 8)")
    
print("working on serial port \"" + ser.name + "\"")
#ser.name returns name of port - in case of LinkIt ONE COM8 or COM7 (for debug)

#=======sending data============#
message = "this string we wwnt to send to LinkIt ONE"
ser.write(message.encode())
#see how I used .encode() on string. If that isn't done, it doesn't work
ser.write('\r'.encode())
#LinkIt ONE code reads up to carriage return character so we must send it after string
#it could be included in string; you don't have to send it separately but .encode() must be called on it

#=======reading data============#
#read data forever
while True:
    a=ser.readline().strip()
    #ser.readline() waits for first newline character("\n") and returns all characters before it
    #.strip() method clears whitespace before and after string - purely cosmetic
    print(a)
    #note that it will hang program if no newline character is received
    #if newline character isn't expected, using .read() method might be better choice as it only
    #returns last character
	
	
