plot.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4. from matplotlib import style
  5. import numpy as np
  6. import random
  7. import serial
  8. #initialize serial port
  9. ser = serial.Serial()
  10. ser.port = "COM3"
  11. # ser.port = '/dev/ttyS2' #Arduino serial port
  12. ser.baudrate = 115200
  13. ser.timeout = 10 #specify timeout when using readline()
  14. ser.open()
  15. if ser.is_open==True:
  16. print("\nAll right, serial port now open. Configuration:\n")
  17. print(ser, "\n") #print serial parameters
  18. # Create figure for plotting
  19. fig = plt.figure()
  20. ax = fig.add_subplot(1, 1, 1)
  21. xs = [] # time
  22. ys = [] # shoult temp
  23. rs = [] # is temp
  24. # This function is called periodically from FuncAnimation
  25. last_i = 1
  26. def animate(i, xs, ys):
  27. global last_i
  28. #Aquire and parse data from serial port
  29. line=ser.readline() #ascii
  30. try:
  31. line.decode()
  32. except:
  33. return
  34. line_as_list = line.split(b',')
  35. i = int(line_as_list[0].strip())
  36. if (i-last_i) < 1000:
  37. return
  38. print(line.decode().strip())
  39. last_i = i
  40. should_float = float(line_as_list[1].strip())
  41. is_float = float(line_as_list[2].strip())
  42. # Add x and y to lists
  43. xs.append(i)
  44. ys.append(should_float)
  45. rs.append(is_float)
  46. # Limit x and y lists to 20 items
  47. #xs = xs[-20:]
  48. #ys = ys[-20:]
  49. # Draw x and y lists
  50. ax.clear()
  51. ax.plot(xs, ys, label="Experimental Probability")
  52. ax.plot(xs, rs, label="Theoretical Probability")
  53. # Format plot
  54. plt.xticks(rotation=45, ha='right')
  55. plt.subplots_adjust(bottom=0.30)
  56. plt.title('This is how I roll...')
  57. plt.ylabel('Relative frequency')
  58. plt.legend()
  59. plt.axis([None, None, 0, 120]) #Use for arbitrary number of trials
  60. #plt.axis([1, 100, 0, 1.1]) #Use for 100 trial demo
  61. # Set up plot to call animate() function periodically
  62. ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys))
  63. plt.show()