学习MPU6050时想看看输出数据的波形图,奈何当时唯一找到的一个可以串输出波形的串口助手还要收费,只能花点时间用python写一个,借鉴了很多文章和chatGPT这里不一一列举了。
主要用到的库:serial串口库,matplotlib画图库。
程序思路:
1.配置串口
2.打开串口接收最初100数据,并绘图
3.使用FuncAnimation更新数据和绘制动画。update是每次更新data中的最后一个数,新数据从最后插入,旧数据从前面丢掉
import serial
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
""" 单片机传输数据格式:"数字\n",例如Usart_SendStr("59\n")。"""
# 配置串口参数
ser = serial.Serial('COM4', 115200) # 将'COM1'替换为你的串口号和波特率
# 创建一个图形窗口
fig, ax = plt.subplots()
data = []
buffer = 0
i = 0
try:
#打开串口
if not ser.is_open:
ser.open()
#接收最初100个数据
while len(data) < 100:
value = ser.readline().strip().decode('utf-8') #按行接收,以"\n"为分隔符
#print(value)
if value != '': #避免最开始一行只接收到"\n"
buffer = int(value)
#print(buffer)
data.append(buffer)
x = np.linspace(0, 10, 100) #x轴
line, = ax.plot(x, data) #初始时刻的曲线
print("初始绘图结束")
# 读取并绘制串口数据
def update(frame):
global buffer, data, i
ser.flushInput() #清空缓冲区
value = ser.readline().strip().decode('utf-8')
while value == '': #避免最开始一行只接收到"\n"
continue
buffer = int(value)
data = data[1:]
data.append(buffer)
line.set_ydata(data) #根据更新 y 数据
ax.set_ylim(min(data)-20, max(data)+20) #实时改变y轴范围
i += 1
print(buffer)
print(i)
return line
# 创建动画
ani = FuncAnimation(fig, update, frames=1000, interval=20)
plt.title('Sine Curve Animation')
plt.xlabel('time')
plt.ylabel('AX')
plt.grid(True)
plt.show()
except KeyboardInterrupt:
pass
finally:
ser.close()
#错误总结,update中data.append(buffer)写成了data.append(value),导致data中混入了字符,在100帧后程序出错。
#frames是动画绘制的帧数
# ser.flushInput() 必须加,不然读出来的数据就是几秒以前存在缓冲区里的