所以我试图编写一个程序,该程序将获取串行数据,然后绘制该数据。数据是从0到0xfff的128个数字。我不断收到有关“ Nonetype”对象的神秘错误消息,因为没有属性更新。我相信我的其余代码都能正常工作,因为我已经调试了大多数存储的数据,并且似乎按照我期望的方式对其进行了格式化。我没有错过任何大小的矩阵错误。只是Nonetype错误。我相信该错误位于Get_Serial_Data或实际行ani = animation.funcAnimation中。任何帮助,将不胜感激。这是我的代码:
from threading import Thread
import matplotlib.animation as animation
from matplotlib.lines import Line2D
from matplotlib import style
import serial
import time
import numpy as np
import matplotlib.pyplot as plt
class serialPlot():
def __init__(self, ax, serialPort='/dev/ttyUSB0', serialBaud=115200,
plotLength=127, dataNumBytes=2):
self.port = serialPort
self.ax = ax
self.xdata = np.arange(0, 127)
self.data = np.arange(0, 127)
self.line = Line2D(self.xdata, self.data)
self.ax.add_line(self.line)
self.ax.set_xlim(0, 128)
self.ax.set_ylim(0, 0xfff)
self.baud = serialBaud
self.plotMaxLength = plotLength
self.dataNumBytes = dataNumBytes
self.rawData = bytearray(dataNumBytes)
# sets up a byte array to accept input 2 bytes in size
self.isRun = True
self.isReceiving = False
self.thread = None
# self.csvData = []
print('Trying to connect to: ' + str(serialPort) + ' at '
+ str(serialBaud) + ' BAUD.')
try:
self.serialConnection = serial.Serial(serialPort, serialBaud,
timeout=4)
print('Connected to ' + str(serialPort) + ' at '
+ str(serialBaud) + ' BAUD.')
except:
print("Failed to connect with " + str(serialPort)
+ ' at ' + str(serialBaud) + ' BAUD.')
def readSerialStart(self):
if self.thread is None:
self.thread = Thread(target=self.backgroundThread)
self.thread.start()
# Block till we start receiving values
if self.isReceiving is not True:
time.sleep(0.000000001)
def Get_Serial_Data(self, frame):
# The first time we get data it most likely is in the middle
self.rawdata = self.serialConnection.readline()
# So we get the data back-to-back because second time will be all data
self.rawdata = self.serialConnection.readline()
# The data is CSV so we split at the commas and put into an array
arr = str(self.rawdata).split(',')
# The first number has a b' do to python's formating so we split the '
first_number = str(arr[0]).split('\'')
# turn the array into an numpy array while discarding b' and \r\n
self.data = np.array(arr[1:128])
# Reinsert the first number into the numpy array
self.data = np.insert(self.data, 0, first_number[1], None)
self.ax.figure.canvas.draw()
self.line.set_data(self.xdata, self.data)
return self.line,
# self.csvData.append(self.data[-1])
def backgroundThread(self): # retrieve data
time.sleep(.000000001) # give some buffer time for retrieving data
self.serialConnection.reset_input_buffer()
while (self.isRun):
self.serialConnection.readinto(self.rawData)
self.isReceiving = True
# print(self.rawData)
def close(self):
self.isRun = False
# self.thread.join()
self.serialConnection.close()
print('Disconnected...')
# df = pd.DataFrame(self.csvData)
# df.to_csv('/home/rikisenia/Desktop/data.csv')
# def init():
# line.set_data(xdata, [np.nan] * len(xdata))
# return line,
def main():
port = input("Which port # is KL25Z connected to? ")
portName = 'COM' + port # for windows users
# portName = '/dev/ttyUSB0' #for Linux
baudRate = (115200)
maxPlotLength = (128)
dataNumBytes = (2) # number of bytes of 1 data point
# Initialize a serial connection all required variables.
fig, ax = plt.subplots()
s = serialPlot(ax, portName, baudRate, maxPlotLength, dataNumBytes)
# plt.yticks(np.arange(0,0xfff,step=500))
# plt.xticks(np.arange(0,127,step=8))
# ax = fig.add_subplot(1,1,1)
# ax.plot(np.arange(0,127),label="Light")
style.use("fivethirtyeight")
plt.xlabel('Registry')
plt.ylabel('Light')
ani = animation.FuncAnimation(fig, s.Get_Serial_Data, blit=False)
if len(s.data) is len(s.xdata):
print("the length of both data is the same.\n")
else:
print("The two arrays have different sizes.\n")
plt.show()
# ans = input("Exit? ")
# if (ans == "y"):
# s.close()
# exit()
# s.close()
if __name__ == '__main__':
main()
Traceback (most recent call last):
File "D:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 1238, in _on_timer
ret = func(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\matplotlib\animation.py", line 1460, in _step
still_going = Animation._step(self, *args)
File "D:\Anaconda3\lib\site-packages\matplotlib\animation.py", line 1191, in _step
self._draw_next_frame(framedata, self._blit)
File "D:\Anaconda3\lib\site-packages\matplotlib\animation.py", line 1210, in _draw_next_frame
self._draw_frame(framedata)
File "D:\Anaconda3\lib\site-packages\matplotlib\animation.py", line 1762, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
File "c:\Users\Joshua Edwards\AppData\Roaming\SPB_Data\.spyder-py3\FastSerialPlot.py", line 70, in Get_Serial_Data
self.ax.figure.canvas.draw()
File "D:\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 402, in draw
self.figure.draw(self.renderer)
File "D:\Anaconda3\lib\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "D:\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1649, in draw
renderer, self, artists, self.suppressComposite)
File "D:\Anaconda3\lib\site-packages\matplotlib\image.py", line 138, in _draw_list_compositing_images
a.draw(renderer)
File "D:\Anaconda3\lib\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "D:\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 2628, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "D:\Anaconda3\lib\site-packages\matplotlib\image.py", line 138, in _draw_list_compositing_images
a.draw(renderer)
File "D:\Anaconda3\lib\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "D:\Anaconda3\lib\site-packages\matplotlib\lines.py", line 728, in draw
self.recache()
File "D:\Anaconda3\lib\site-packages\matplotlib\lines.py", line 644, in recache
yconv = self.convert_yunits(self._yorig)
File "D:\Anaconda3\lib\site-packages\matplotlib\artist.py", line 195, in convert_yunits
return ax.yaxis.convert_units(y)
File "D:\Anaconda3\lib\site-packages\matplotlib\axis.py", line 1530, in convert_units
ret = self.converter.convert(x, self.units, self)
File "D:\Anaconda3\lib\site-packages\matplotlib\category.py", line 53, in convert
unit.update(values)
AttributeError: 'NoneType' object has no attribute 'update'