用Python接收串口数据并实时显示
时间: 2025-06-29 21:10:36 浏览: 5
### 使用 Python 读取串口数据并实现实时显示
为了实现通过 Python 从串口接收数据并实时显示的功能,通常会使用 `pyserial` 库来处理串口通信,并结合图形界面库如 `matplotlib` 来创建动态图表。下面是一个完整的示例程序,展示了如何设置这样的功能。
#### 安装所需库
首先需要安装两个主要依赖项:
- pyserial:用于与串行端口交互。
- matplotlib:用来绘制图形化表示的数据流。
可以通过 pip 工具轻松安装这两个包:
```bash
pip install pyserial matplotlib
```
#### 示例代码
接下来展示一段简单的 Python 脚本,它能够持续不断地从指定的 COM 端口中获取数值型传感器测量值(假设每条记录都是一个浮点数),并将这些新到达的信息即时更新到折线图上。
```python
import serial
from threading import Thread
import time
import collections
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import struct
class RealtimePlot:
def __init__(self, max_entries=30):
self._max_entries = max_entries
self._buf = collections.deque([0.0]*max_entries, maxlen=max_entries)
fig, ax = plt.subplots()
self.line, = ax.plot([], [])
self.ax = ax
self anim = animation.FuncAnimation(fig, self.update_line, interval=50)
@property
def y_data(self):
return list(self._buf)
def add_y(self, y):
self._buf.append(y)
def update_line(self, i):
self.line.set_xdata(range(len(self.y_data)))
self.line.set_ydata(self.y_data)
self.ax.relim()
self.ax.autoscale_view()
def read_from_port(ser, plot_window):
while True:
try:
reading = ser.read_until().strip() # 假设每一行代表一次新的采样
value = float(reading.decode('utf-8'))
plot_window.add_y(value)
except Exception as e:
print(f"Error occurred during data processing: {e}")
finally:
time.sleep(0.1)
if __name__ == '__main__':
port_name = '/dev/ttyUSB0' # Linux 下可能是 /dev/ttyUSB* 或者对于 Windows 是 'COM3'
baud_rate = 9600
with serial.Serial(port_name, baud_rate, timeout=None) as ser:
window = RealtimePlot(max_entries=100)
thread = Thread(target=read_from_port, args=(ser, window))
thread.daemon = True
thread.start()
plt.show()
```
此段代码实现了几个重要特性:
- 创建了一个名为 `RealtimePlot` 的类,负责管理缓冲区内的历史数据以及刷新 Matplotlib 图形对象;
- 启动后台线程不断尝试从给定串口号处拉取消息帧,解析成有效负载之后追加至可视化窗口中去;
- 主函数部分配置好物理连接参数后即进入事件循环等待用户关闭应用程序为止[^4]。
阅读全文
相关推荐
















