2

我是编程新手,几周后制作了一些程序来做简单的事情;比如从 arduino 捕获串行数据并将其保存到文本文件中。现在我想结合几件事。我想使用 python 来捕获串行数据,提示端口和文件名,获取该数据并实时绘制它,然后当 arudino 不再连接时,保存并关闭文件。这是我到目前为止的代码。

问题是图表根本不是实时的。传感器几乎没有变化。我有时也会收到 matplotlib 贬值警告。我想知道是否有快速修复或者我是否遗漏了一些重要的东西。太感谢了!

    import numpy
    import matplotlib.pyplot as plt
    import math
    import time
    import pylab
    from drawnow import drawnow
    import csv
    import serial
    import os
    import glob
    import sys

    filename = raw_input("Save file as: ")
    saveFile = open(filename, 'w')

    print "Available ports: "

    def serial_port():
         if sys.platform.startswith('win'):
             ports = ['COM%s' % (i + 1) for i in range (256)]
        elif sys.platform.startswith('linux') or      sys.platform.startswith('cygwin'):
            ports = glob.glob('/dev/tty/[A-Za-z]*')
         elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.*')
        else:
            raise EnvironmentError('Unsupported Platform')

        result = []
        for port in ports:
            try:
        s = serial.Serial(port)
        s.close()
        result.append(port)

    except (OSError, serial.SerialException):
        pass
return result

    if __name__ == '__main__':
        print serial_port()

    serialport = raw_input("Enter Port: ")
    port1 = serialport

    print "Connecting to port...", port1

    arduino1 = serial.Serial(port1, 115200)

    print "Arduino Detected"


    #create arrays with the following names
    Time = []
    analog0 = []
    analog1 = []
    voltage0 = []
    voltage1 = []
    Temp = []
    RH = []

    #reading data from the serial port
    #telling Matplot.lib to plot live data
    plt.ion()

    #creates a function to make a plot we want
     def Fig1():
        plt.plot(analog0, 'r-')
        plt.title("Analog0 Data")
        plt.ylim(405, 425)
        plt.grid(True)
        plt.ylabel("analog")
        plt.xlabel("milliseconds")

    x = os.path.exists(port1)

    while x==0:
        arduinoString = arduino1.readline()
        saveFile.write(arduinoString)
        dataArray = arduinoString.split(',')
        time = float(dataArray[0])
        a0 = float(dataArray[1])
        a1 = float(dataArray[2])
        v0 = float(dataArray[3])
        v1 = float(dataArray[4])
        temp = float(dataArray[5])
        rh = float(dataArray[6])
          #filling our arrays with those new data values (floats)
        Time.append(time)
        analog0.append(a0)
        analog1.append(a1)
        voltage0.append(v0)
        voltage1.append(v1)
        Temp.append(temp)
        RH.append(rh)

        drawnow(Fig1)
        plt.pause(0.00010)

    else:
        saveFile.close()
4

1 回答 1

0

我也有同样的问题。

它是通过使用set_data()类似打击链接解决的。

立即绘制和 Matplotlib

于 2020-10-22T09:43:18.473 回答