plot.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/env python3
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import serial
  5. import sys,csv,time
  6. #initialize serial port
  7. ser = serial.Serial()
  8. ser.port = "COM3"
  9. # ser.port = '/dev/ttyS2' #Arduino serial port
  10. ser.baudrate = 115200
  11. ser.timeout = 10 #specify timeout when using readline()
  12. ser.open()
  13. ser.flushInput()
  14. if ser.is_open==True:
  15. print("\nAll right, serial port now open. Configuration:\n")
  16. print(ser, "\n") #print serial parameters
  17. '''
  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. '''
  25. plot_window = 60
  26. x_var = np.array(np.zeros([plot_window]))
  27. y1_var = np.array(np.zeros([plot_window]))
  28. y2_var = np.array(np.zeros([plot_window]))
  29. plt.ion()
  30. fig, ax = plt.subplots()
  31. # plt.axis([None, None, 0, 120])
  32. line1, = ax.plot(x_var, y1_var)
  33. line2, = ax.plot(x_var, y2_var)
  34. count = 0
  35. while True:
  36. while ser.inWaiting()==0:
  37. plt.pause(.1)
  38. line=ser.readline()
  39. try:
  40. count = count + 1
  41. if len(line) < 3:
  42. continue
  43. line = line.decode()
  44. print(line.rstrip("\n"))
  45. line_as_list = line.split(',')
  46. if len(line_as_list) < 3:
  47. continue
  48. i = int(line_as_list[0].strip())
  49. should_float = float(line_as_list[1].strip())
  50. is_float = float(line_as_list[2].strip())
  51. if len(sys.argv) > 1:
  52. with open(sys.argv[1],"a") as f:
  53. writer = csv.writer(f,delimiter=",")
  54. writer.writerow([i, should_float, is_float])
  55. x_var = np.append(x_var, i)
  56. x_var = x_var[1:plot_window+1]
  57. y1_var = np.append(y1_var, should_float)
  58. y1_var = y1_var[1:plot_window+1]
  59. y2_var = np.append(y2_var, is_float)
  60. y2_var = y2_var[1:plot_window+1]
  61. # print(x_var)
  62. # print(y1_var)
  63. # print(y2_var)
  64. line1.set_xdata(x_var[-count:])
  65. line2.set_xdata(x_var[-count:])
  66. line1.set_ydata(y1_var[-count:])
  67. line2.set_ydata(y2_var[-count:])
  68. ax.relim()
  69. ax.autoscale_view()
  70. fig.canvas.draw()
  71. fig.canvas.flush_events()
  72. except Exception as ex:
  73. print(ex)
  74. continue
  75. '''
  76. # Draw x and y lists
  77. ax.clear()
  78. ax.plot(xs, ys, label="Temp Dial")
  79. ax.plot(xs, rs, label="Temp Sensor")
  80. # Format plot
  81. plt.xticks(rotation=45, ha='right')
  82. plt.subplots_adjust(bottom=0.30)
  83. plt.title('This is how I roll...')
  84. plt.ylabel('Relative frequency')
  85. plt.legend()
  86. plt.axis([None, None, 0, 120])
  87. #plt.axis([1, 100, 0, 1.1]) #Use for 100 trial demo
  88. '''