在函数[Python]中找不到串行句柄

时间:2016-07-18 15:23:21

标签: python matplotlib

我是python的新手。我正在编写一个数据记录程序,想要打开一个串口,然后从中读取。

我的问题是在我的main()中调用它:

# Handle serial
ser = serial.Serial(strPort, 9600)

不允许我在其他函数中调用ser句柄上的方法。我应该上课还是最好的方法?

以下是错误消息:

line 164, in updateData
    line = ser.readline().rstrip()
NameError: name 'ser' is not defined

以下是代码:

# Uncomment the next two lines if you want to save the animation
import matplotlib
# matplotlib.use("Agg")

import sys
import serial
import argparse
import csv
import numpy
from matplotlib.pylab import *
from mpl_toolkits.axes_grid1 import host_subplot
import matplotlib.animation as animation

'''
ax03.legend([p031,p032], [p031.get_label(),p032.get_label()])
'''

def main():
    # Sent for figure
    font = {'size': 9}
    matplotlib.rc('font', **font)

    # Setup figure and subplots
    f0 = figure(num=0, figsize=(12, 10))  # , dpi = 100)
    f0.suptitle("Sensor Data", fontsize=12)
    ax01 = subplot2grid((3, 2), (1, 0))
    #ax02 = subplot2grid((4, 2), (1, 1))
    ax02 = ax01.twinx()
    ax03 = subplot2grid((3, 2), (0, 0), colspan=2, rowspan=1)
    ax04 = subplot2grid((3, 2), (1, 1))
    ax05 = subplot2grid((3, 2), (2, 0))
    ax06 = subplot2grid((3, 2), (2, 1))
    subplots_adjust(left=None, bottom=None, right=None,
                    top=None, wspace=0.3, hspace=0.3)

    # Set titles of subplots
    ax01.set_title('Heart Rate Quality and Sample Frequency')
    ax03.set_title('Heart Rate')
    ax04.set_title('Step Rate')
    ax05.set_title('Perfusion Index')
    ax06.set_title('Raw PPG')

    # set y-limits
    ax01.set_ylim(-1, 5)
    ax02.set_ylim(100, 500)
    ax03.set_ylim(30, 140)
    ax04.set_ylim(-50, 250)
    ax05.set_ylim(0, 500)
    ax06.set_ylim(0, 50000)

    # sex x-limits
    ax01.set_xlim(0, 50.0)
    # ax02.set_xlim(0,50.0)
    ax03.set_xlim(0, 50.0)
    ax04.set_xlim(0, 50.0)
    ax05.set_xlim(0, 50.0)
    ax06.set_xlim(0, 50.0)

    # Turn on grids
    ax01.grid(True)
    # ax02.grid(True)
    ax03.grid(True)
    ax04.grid(True)
    ax05.grid(True)
    ax06.grid(True)

    # set label names
    ax01.set_xlabel("t[s]")
    ax01.set_ylabel("HRQ")
    ax02.set_xlabel("t[s]")
    ax02.set_ylabel("samples[Hz]")
    ax03.set_xlabel("t[s]")
    ax03.set_ylabel("bpm")
    ax04.set_xlabel("t[s]")
    ax04.set_ylabel("Steps/min")
    ax05.set_xlabel("t[s]")
    ax05.set_ylabel("AC/DC ratio")
    ax06.set_xlabel("t[s]")
    ax06.set_ylabel("raw PS sample")

    # Data Placeholders
    t = zeros(0)
    hr = zeros(0)
    HRQ = zeros(0)
    Fs = zeros(0)
    stepRate = zeros(0)
    ADCGain = zeros(0)
    pI = zeros(0)
    rawPPG = zeros(0)
    ser = zeros(0)

    # set plots
    p011, = ax01.plot(t, HRQ, 'c-', label="HRQ", linewidth=2)

    p021, = ax02.plot(t, ADCGain, 'r-', label="Sample Frequency", linewidth=2)

    p031, = ax03.plot(t, hr, 'b-', label="Heart Rate", linewidth=2)

    p041, = ax04.plot(t, stepRate, 'b-', label="Step Rate", linewidth=2)

    p051, = ax05.plot(t, pI, 'y-', label="Perfusion Index", linewidth=2)

    p061, = ax06.plot(t, rawPPG, 'g-', label="Raw PPG", linewidth=2)

    # set lagends
    ax01.legend([p011, p021], [p011.get_label(), p021.get_label()], loc=2)
    #ax02.legend([p021], [p021.get_label()])
    ax03.legend([p031], [p031.get_label()], loc=2)
    ax04.legend([p041], [p041.get_label()], loc=2)
    ax05.legend([p051], [p051.get_label()], loc=2)
    ax06.legend([p061], [p061.get_label()], loc=2)

    # Data Update
    xmin = 0.0
    xmax = 50.0
    x = 0.0

    # create parser
    parser = argparse.ArgumentParser(description="LDR serial")
    # add expected arguments
    parser.add_argument('--port', dest='port', required=True)

    # parse args
    args = parser.parse_args()

    #strPort = '/dev/tty.usbserial-A7006Yqh'
    strPort = args.port

    print('reading from serial port %s...' % strPort)

    # Handle serial
    ser = serial.Serial(strPort, 9600)

    print('plotting data...')

    # Logfile writer
    # open('test.csv','w') as csvfile
    #logwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    # interval: draw new frame every 'interval' ms
    # frames: number of frames to draw
    simulation = animation.FuncAnimation(
    f0, updateData, blit=False, frames=1000, interval=100, repeat=True)

    # Uncomment the next line if you want to save the animation
    # simulation.save(filename='sim.mp4',fps=1,dpi=300)
    plt.show()


def updateData(self):
    global x
    global t
    global ser

    global hr
    global HRQ
    global Fs
    global ADCGain
    global stepRate
    global pI
    global rawPPG

    try:
        line = ser.readline().rstrip()
        data = [float(val) for val in line.split()]
        # print data
        print(data)

        if(len(data) == 9):
            # log data
            for i in range(len(data)):
                out_string = ""
                out_string += str(data[i])
            # logwriter.writerow(out_string)

            # update variables
            tmpT = data[0]
            tmpFs = data[1]
            tmpStepRate = data[2]
            tmpHr = data[3]
            tmpPI = data[4]
            tmpHRQ = data[5]
            tmpRawPPG = data[6]

    except KeyboardInterrupt:
        print('exiting')

    hr = append(hr, tmpHr)
    HRQ = append(HRQ, tmpHRQ)
    Fs = append(Fs, tmpFs)
    stepRate = append(stepRate, tmpStepRate)
    pI = append(pI, tmpPI)
    rawPPG = append(rawPPG, tmpRawPPG)

    t = append(t, x)

    x += 1

    p011.set_data(t, HRQ)

    p021.set_data(t, Fs)

    p031.set_data(t, hr)

    p041.set_data(t, stepRate)

    p051.set_data(t, pI)

    p061.set_data(t, rawPPG)

    if x >= xmax - 10.00:
        p011.axes.set_xlim(x - xmax + 10.0, x + 10.0)
        p021.axes.set_xlim(x - xmax + 10.0, x + 10.0)
        p031.axes.set_xlim(x - xmax + 10.0, x + 10.0)
        p041.axes.set_xlim(x - xmax + 10.0, x + 10.0)
        p051.axes.set_xlim(x - xmax + 10.0, x + 10.0)
        p061.axes.set_xlim(x - xmax + 10.0, x + 10.0)

    return p011, p021, p031, p041, p051, p061



# Call main
if __name__ == '__main__':
    main()

0 个答案:

没有答案