'''
A simple program to interrogate the print string from an arduino nano
convert string to list of floats, and plot on bar graph.

For a description of how the code works see NOTES at end of code

20/08/2018 smooth_jamie@outlook.com

'''

import time
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation

ser = serial.Serial(
        port='COM8',
        baudrate=9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1,
)

ser.close()
ser.open()

fig, ax = plt.subplots()

x_data = ['Violet','Blue','Green','Yellow','Orange','Red']

def animate(i):
    
    ax.clear()
    ax.set_ylim(0,60000)
    ax.set_title('Wavelength intensity')
    ax.set_xlabel('Wavelength')
    ax.set_ylabel('Amplitude (units)')
    return ax.bar(x_data, main(), color='grey')

def main():

    output = ser.readline()
    data = str(output).split(',')
    
    del data[0]
    if data:
            del data[6]
            y_data = [float(values) for values in data]
            
            print (y_data)
            return y_data
    else:
        y_data = [0,0,0,0,0,0]
        
        return y_data

ani = animation.FuncAnimation(fig, animate, interval=0, blit=True)
plt.show()
