我想在接收串口数据并写入数据这个方法里,同时进行折线图绘制串口数据,方法为: def writ_excel(self, TIME): uart_r = self.uart_r received_bytes_list = [] start_time = time.time() while (time.time() - start_time <= 40): read_byte = uart_r.read(1) if read_byte != b'': print(".", end="") received_bytes_list.append(read_byte.decode()) if len(received_bytes_list) == 0: print("Warning: timeout!") else: print("Received data successfully!") # Save to Excel file received_bytes = ''.join(received_bytes_list) received_data = received_bytes.split() received_data_8 = [received_data[i: i + 8] for i in range(0, len(received_data), 8)] df = pd.DataFrame(columns=['0', '1', '2', '3', '4', '5', '6', '7']) for i, str in enumerate(received_data_8): print("Write to excel line:", i, str) if (len(str) < 8): print("Populate data.") str += [0] * (8 - len(str)) df.loc[i] = str df.to_excel('%s.xlsx' % TIME)
时间: 2024-03-13 11:42:39 浏览: 79
好的,您可以在这个方法中添加绘制折线图的代码。具体来说,您需要在方法开始时创建一个Matplotlib图形窗口和坐标轴对象,然后在每次接收到数据后更新折线图。下面是一个示例代码:
```python
import matplotlib.pyplot as plt
import pandas as pd
def writ_excel(self, TIME):
uart_r = self.uart_r
received_bytes_list = []
start_time = time.time()
# 创建Matplotlib图形窗口和坐标轴对象
fig, ax = plt.subplots()
line, = ax.plot([], [])
ax.set_xlim(0, 100)
ax.set_ylim(0, 1024)
ax.set_title('Real-time data')
xdata, ydata = [], []
while (time.time() - start_time <= 40):
read_byte = uart_r.read(1)
if read_byte != b'':
print(".", end="")
received_bytes_list.append(read_byte.decode())
# 更新折线图
data = ''.join(received_bytes_list).strip()
if data:
x, y = data.split(',')
xdata.append(int(x))
ydata.append(int(y))
line.set_data(xdata, ydata)
ax.relim()
ax.autoscale_view()
fig.canvas.draw()
if len(received_bytes_list) == 0:
print("Warning: timeout!")
else:
print("Received data successfully!")
# 保存数据到Excel文件
received_bytes = ''.join(received_bytes_list)
received_data = received_bytes.split()
received_data_8 = [received_data[i: i + 8] for i in range(0, len(received_data), 8)]
df = pd.DataFrame(columns=['0', '1', '2', '3', '4', '5', '6', '7'])
for i, str in enumerate(received_data_8):
print("Write to excel line:", i, str)
if (len(str) < 8):
print("Populate data.")
str += [0] * (8 - len(str))
df.loc[i] = str
df.to_excel('%s.xlsx' % TIME)
```
在这个示例代码中,我们首先在方法开始时创建了Matplotlib图形窗口和坐标轴对象。然后,在每次接收到数据时,我们更新了数据列表,并解析接收到的数据并更新折线图。最后,我们在保存数据到Excel文件之前,将数据存储在DataFrame对象中。
请注意,这只是一个示例代码,您需要根据您的具体需求进行修改和扩展。
阅读全文