1

我可以通过pyserial从串口设备捕获数据,此时我只能将数据导出到文本文件,文本文件的格式如下,它有3列

>21 21 0 
>
>41 41 0.5
>
>73 73 1
>    
....
>2053 2053 5
>
>2084 2084 5.5
>
>2125 2125 6

现在我想用matplotlib生成实时图有2个图(x,y)x,y是第二列和第三列,第一列,'>',没有数据的行可以删除

谢谢大家!

==============================

更新:今天,在遵循这些指南之后

http://www.blendtechnologies.com/realtime-plot-of-arduino-serial-data-using-python/231 http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis pyserial - 如何读取从串行设备发送的最后一行

现在我可以使用线程进行绘图,但 eliben 说这个 Guis 每次只绘制单个值,这给我带来了很大的限制,因为我的目的是绘制 2 或 3 列,这里的代码是从 blendedtechnologies 修改的

这是串行处理程序:从线程导入线程

import time
import serial

last_received = ''
def receiving(ser):
    global last_received
    buffer = ''
    while True:
        buffer = buffer + ser.read(ser.inWaiting())
        if '\n' in buffer:
            lines = buffer.split('\n') # Guaranteed to have at least 2 entries
            last_received = lines[-2]
            #If the Arduino sends lots of empty lines, you'll lose the
            #last filled line, so you could make the above statement conditional
            #like so: if lines[-2]: last_received = lines[-2]
            buffer = lines[-1]


class SerialData(object):
    def __init__(self, init=50):
        try:
            self.ser = ser = serial.Serial(
                port='/dev/ttyS0',
                baudrate=9600,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=0.1,
                xonxoff=0,
                rtscts=0,
                interCharTimeout=None
            )
        except serial.serialutil.SerialException:
            #no serial connection
            self.ser = None
        else:
            Thread(target=receiving, args=(self.ser,)).start()

    def next(self):
        if not self.ser:
            return 100  #return anything so we can test when Arduino isn't connected
                #return a float value or try a few times until we get one
        for i in range(40):
            raw_line = last_received[1:].split(' ').pop(0)
            try:
                return float(raw_line.strip())
            except ValueError:
                print 'bogus data',raw_line
                time.sleep(.005)
        return 0.
    def __del__(self):
        if self.ser:
            self.ser.close()

if __name__=='__main__':
    s = SerialData()
    for i in range(500):
        time.sleep(.015)
        print s.next()

对我来说,我修改了这个部分,以便它可以获取我的第一列数据

for i in range(40):
                raw_line = last_received[1:].split(' ').pop(0)
                try:
                    return float(raw_line.strip())
                except ValueError:
                    print 'bogus data',raw_line
                    time.sleep(.005)
            return 0.

并根据 GUI 文件上的这些功能生成图形

from Arduino_Monitor import SerialData as DataGen
def __init__(self):
        wx.Frame.__init__(self, None, -1, self.title)

        self.datagen = DataGen()
        self.data = [self.datagen.next()]

...................................................

def init_plot(self):
        self.dpi = 100
        self.fig = Figure((3.0, 3.0), dpi=self.dpi)

        self.axes = self.fig.add_subplot(111)
        self.axes.set_axis_bgcolor('black')
        self.axes.set_title('Arduino Serial Data', size=12)

        pylab.setp(self.axes.get_xticklabels(), fontsize=8)
        pylab.setp(self.axes.get_yticklabels(), fontsize=8)

        # plot the data as a line series, and save the reference 
        # to the plotted line series
        #
        self.plot_data = self.axes.plot(
            self.data, 
            linewidth=1,
            color=(1, 1, 0),
            )[0]

所以我的下一个问题是如何实时抓取至少 2 列并将 2 列的数据传递给它可以生成 2 轴图形的 GUI。

self.plot_data.set_xdata(np.arange(len(self.data)))  #my 3rd column data
self.plot_data.set_ydata(np.array(self.data))        #my 2nd column data
4

3 回答 3

2

好吧,这会读取您的字符串并将数字转换为浮点数。我假设您将能够根据需要进行调整。

import numpy as np
import pylab as plt

str = '''>21 21 0 
>
>41 41 0.5
>
>73 73 1
>
>2053 2053 5
>
>2084 2084 5.5
>
>2125 2125 6'''
nums = np.array([[float(n) for n in sub[1:].split(' ') if len(n)>0] for sub in str.splitlines() if len(sub)>1])

fig = plt.figure(0)
ax = plt.subplot(2,1,1)
ax.plot(nums[:,0], nums[:,1], 'k.')
ax = plt.subplot(2,1,2)
ax.plot(nums[:,0], nums[:,2], 'r+')
plt.show()
于 2011-11-29T08:48:20.613 回答
1

在这里,您有一个 Eli Bendersky 的示例,说明如何绘制从串行端口到达的数据

于 2011-11-25T22:55:27.763 回答
0

一段时间前我遇到了同样的问题。我一遍又一遍地浪费了很多相同的东西。所以我为它写了一个python包。

https://github.com/girish946/plot-cat

你只需要编写从串口获取数据的逻辑。

示例在这里:https ://github.com/girish946/plot-cat/blob/master/examples/test-ser.py

于 2016-08-26T16:28:26.147 回答