import serial
import matplotlib.pyplot as plt
import numpy as np

connected = False

ser = serial.Serial('/dev/tty.usbserial-FT94TKFS', 9600) #sets up serial connection (make sure baud rate is correct - matches Arduino)

while not connected:
    serin = ser.read()
    connected = True
    
plt.ion()                    # animation mode

length = 500                 # number of datapoints
y = [0]*length               #create empty variable of length of test


yline, = plt.plot(y)         # sets up future lines to be modified

plt.ylim(20,30)              # sets the y axis limits

for i in range(length):     # while you are taking data
    byte2 = 0
    byte3 = 0
    byte4 = 0
    ser.flush()
    while 1:
      #
      # find framing 
      #
      byte1 = byte2
      byte2 = byte3
      byte3 = byte4
      byte4 = ord(ser.read())
      if ((byte1 == 1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)):
         break

    low = ord(ser.read())
    high = ord(ser.read())
    value = 256*high + low
    if (value > 511):
        value -= 1024
    V = 2.5 - value*5.0/(20.0*512.0)
    R = 10000.0/(5.0/V-1.0)
    # NHQ103B375R5
    # R25 10000 (O)
    # B (25/85) 3750 (K)
    # R(T(C)) = R(25)*exp(B*(1/(T(C)+273.15)-(1/(25+273.15))))
    B = 3750.0
    R25 =  10000.0
    T = 1.0/(np.log(R/R25)/B+(1/(25.0+273.15))) - 273.15
    y.append(T)   #add new value as int to current list
    

    del y[0]
    
    yline.set_xdata(np.arange(len(y)))
    yline.set_ydata(y)             
    

    plt.pause(0.001)                   #in seconds
    plt.draw()                         #draws new plot


rows = y                # combines lists together
row_arr = np.array(rows)               # creates array from list
np.savetxt("/Users/vjmdupuis/temp/data.txt", row_arr) # save data in file

ser.close() #closes serial connection 