图形化界面由python编写,需使用pyserial模块。数据由STM32通过串口发送。
以下为图形化界面代码。
import serial
import matplotlib.pyplot as plt
import numpy as np
# 设置串口参数
port = 'COM7' # 根据实际情况修改串口号
baud_rate = 115200 # 波特率
ser = serial.Serial(port, baud_rate)
# 创建绘图窗口和坐标轴
fig, ax = plt.subplots()
ax.set_xlim(-100, 100) # 设置坐标轴范围
ax.set_ylim(0, 100)
ax.set_aspect('equal', 'box') # 设置坐标轴纵横比一致
#ax.set_xlabel('X (cm)')
ax.set_ylabel('Y (cm)')
# 绘制圆弧的背景为绿色
theta = np.linspace(np.deg2rad(0), np.deg2rad(180), 100) # 圆弧角度范围
radius = 90 # 圆弧半径
x = radius * np.cos(theta)
y = radius * np.sin(theta)
ax.fill_between(x, y, color='green')
# 创建存储数据的列表
data_points = []
# 循环读取和显示数据
while True:
# 从STM32读取距离数据
data = ser.readline().decode().strip()
distance = float(data)
if distance > 90:
distance = 2
# 距离转换为角度
angle = np.deg2rad(distance * 2)
# 计算距离对应的坐标
x = distance * np.cos(angle)
y = distance * np.sin(angle)
# 绘制红色的数据点
data_point, = ax.plot(x, y, 'ro') # 注意逗号用于解包元组,让data_point成为单个元素
data_points.append(data_point)
# 清除数据点
for data_point in data_points:
data_point.remove()
data_points.clear()
# 绘制扫描线
scan_line, = ax.plot([0, x], [0, y], color='r', linestyle='--')
# 更新绘图窗口
plt.draw()
plt.pause(0.01)#0.01
# 清除扫描线
scan_line.remove()
# 关闭串口
ser.close()