Python-based on pyqtgraph and the serial port communication of the lower computer and realize real-time data drawing

I want to adjust the pid of the lower computer in real time on the upper computer, so I need to look at the waveform and refuse to adjust blindly. At the same time, using pyqtgragh can easily visualize the data dynamically.

Environmental preparation

  • pyserial
pip install pyserial
  • pyqtgraph
pip install pyqtgraph
pip install PyQt5

Basic connection of serial communication

import serial

ser = serial.Serial("COM3", 9600, timeout=1, stopbits=1)
if (ser.isOpen()):
    print("open success")
     # 向端口些数据 字符串必须译码
    ser.write("hello".encode()) 
    while (True):
        line = ser.readline()  
        if(line):
            print(line)
            line=0
else:
	print("open failed")
ser.close()#关闭端口

Serial port dynamic parameter visualization

pyqtgraghThe visualization of dynamic charts is adopted here , and only the code read by the serial port is added.
Students who want to learn more about the specific use of pyqtgraph can refer to my blog: pyqtgragh-dynamic data visualization: drawing static and dynamic data curves

Here I use the Micropython-based pyboard to communicate between the upper and lower computers. In fact, it is fine to print directly, without UART transmission. My sending data is a tuple format data:
Insert picture description here
about how python and Micropython realize tuple host computer communication Reference blog post: Protocol for communication between upper and lower computers developed based on python or Micropython

  • Code printed by serial port of PYB lower computer :
    Insert picture description here
  • The code on the PC side of the host computer :
import pyqtgraph as pg
import serial
import time
'''
上下位USB通信格式:元组
'''        
def ser_plot():
    start = time.time()
    global last_data
    data = ser.readline()
    data = data.decode("utf-8")
    data = str(data)[1:-3] # 将无关字符去除 “\n” 和 b'' 去除
    try:
        data = eval(data) # 转化回元组形式
    except SyntaxError:
        data = last_data
    print(data)
    encoder = data[0]
    encoder_list.append(encoder[1])
    plot1.setData(encoder_list, pen='g')
    accel = data[1]
    accel_list.append(accel[2])
    plot2.setData(accel_list, pen='r')
    last_data = data
    end = time.time()
    print("cost:", end-start)

if __name__ == '__main__':
    encoder_list = []
    accel_list = []
    last_data = 0

    # serial初始化
    ser = serial.Serial('COM3', 9600)
    if (ser.isOpen()):
        print("open success")
    else:
        print("open failed")

    # pyqtgragh初始化
    # 创建窗口
    app = pg.mkQApp()  # 建立app
    win = pg.GraphicsWindow()  # 建立窗口
    win.setWindowTitle(u'pyqtgraph USB下位机串口波形显示工具')
    win.resize(800, 500)  # 小窗口大小
    # 创建图表
    historyLength = 100  # 横坐标长度
    p1 = win.addPlot()  # 把图p加入到窗口中
    p1.showGrid(x=True, y=True)  # 把X和Y的表格打开
    p1.setRange(xRange=[0, historyLength], yRange=[0, 100], padding=0) # x轴和y轴的范围
    p1.setLabel(axis='left', text='编码器值')  # 靠左
    p1.setLabel(axis='bottom', text='时间')
    p1.setTitle('编码器实时数据')  # 表格的名字
    plot1 = p1.plot()
    
    p2 = win.addPlot()  # 把图p加入到窗口中
    p2.showGrid(x=True, y=True)  # 把X和Y的表格打开
    p2.setRange(xRange=[0, historyLength], yRange=[0, 100], padding=0)
    p2.setLabel(axis='left', text='z')  # 靠左
    p2.setLabel(axis='bottom', text='时间')
    p2.setTitle('加速度计实时数据')  # 表格的名字
    plot2 = p2.plot()
    # 设置定时器
    timer = pg.QtCore.QTimer()
    timer.timeout.connect(ser_plot) # 定时刷新数据显示
    timer.start(40) # 多少ms调用一次

    app.exec_()

Real-time effect display

Flip the trolley and turn the wheel separately
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45779334/article/details/113091229