如何在 python 中等待关闭的端口

How to wait for a closed port in python

我使用 INA219 传感器和 Arduino 制作了一个跟踪电池放电电压的设备,Arduino 收集的信息然后发送到串行通信中的 Raspberry pi,目的是 python coding 和 matplotlib,drawnow 模块,输出将实时绘制在 LCD 上, 我已经为 Arduino 设置了一个看门狗功能,如果它无论如何冻结都会重置,但与此同时,我如何使用 pyserial 模块等待关闭的端口再次打开而不被终止? 在下面你可以看到我的 python 代码:

import serial
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.dates import AutoDateLocator, AutoDateFormatter
from drawnow import *
#import csv

Voltage_0 = [0]
Current_0 = [0]
ResInt_0 = [0]
Power_0 = [0]
Voltage_1 = [0]
Current_1 = [0]
ResInt_1 = [0]
Power_1 = [0]
Voltage_4 = [0]
Current_4 = [0]
ResInt_4 = [0]
Power_4 = [0]
Voltage_5 = [0]
Current_5 = [0]
ResInt_5 = [0]
Power_5 = [0]
Time = []
StartTime = 0
PlotTime = 0
PresentTime = 0
i = 0

if __name__ == '__main__':
    arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
plt.ion()
StartTime = datetime.now()
h = StartTime.hour
m = StartTime.minute
s = StartTime.second
PresentTime = StartTime + timedelta(seconds=5)
PlotTime = PresentTime - timedelta(hours= h,minutes= m, seconds= s)
Time.append(PlotTime)

def CreatePlot():
    plt.suptitle('Type AA Battery Discharge Window')

    ax0 = plt.subplot(2,2,1)
    plt.grid(True)
    plt.plot(Time, Voltage_0,'#ff0400', label='V0')
    ax0.set(xlabel='Time', ylabel='Voltage')
    plt.legend(loc='upper center')
    plt.subplots_adjust(wspace=0.05, hspace=0.07)
    locator = AutoDateLocator()
    ax0.xaxis.set_major_locator(locator)
    formatter = AutoDateFormatter(locator)
    ax0.xaxis.set_major_formatter(formatter)
    ax0.xaxis.set_minor_locator(AutoMinorLocator())
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylim(0,1.7)
    ax0.label_outer()

    ax1 = plt.subplot(2,2,2)
    plt.grid(True)
    plt.plot(Time, Voltage_1,'#ffaa00', label='V1')
    ax1.set(xlabel='Time', ylabel='Voltage')
    plt.legend(loc='upper center')
    plt.subplots_adjust(wspace=0.05, hspace=0.07)
    locator = AutoDateLocator()
    ax1.xaxis.set_major_locator(locator)
    formatter = AutoDateFormatter(locator)
    ax1.xaxis.set_major_formatter(formatter)
    ax1.xaxis.set_minor_locator(AutoMinorLocator())
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylim(0,1.7)
    ax1.label_outer()

    ax2 = plt.subplot(2,2,3)
    plt.grid(True)
    plt.plot(Time,Voltage_4, '#fff200', label='V4')
    ax2.set(xlabel='Time', ylabel='Voltage')
    plt.legend(loc='upper center')
    plt.subplots_adjust(wspace=0.05, hspace=0.07)
    locator = AutoDateLocator()
    ax2.xaxis.set_major_locator(locator)
    formatter = AutoDateFormatter(locator)
    ax2.xaxis.set_major_formatter(formatter)
    ax2.xaxis.set_minor_locator(AutoMinorLocator())
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylim(0,1.7)
    ax2.label_outer()

    ax3 = plt.subplot(2,2,4)
    plt.grid(True)
    plt.plot(Time,Voltage_5, '#0af219', label='V5')
    ax3.set(xlabel='Time', ylabel='Voltage')
    plt.legend(loc='upper center')
    plt.subplots_adjust(wspace=0.05, hspace=0.07)
    locator = AutoDateLocator()
    ax3.xaxis.set_major_locator(locator)
    formatter = AutoDateFormatter(locator)
    ax3.xaxis.set_major_formatter(formatter)
    ax3.xaxis.set_minor_locator(AutoMinorLocator())
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylim(0,1.7)
    ax3.label_outer()

while True:
    if arduino.in_waiting > 0:
        arduinoString = arduino.readline().decode('UTF-8').rstrip()
        PresentTime = datetime.now()
        dataArray = arduinoString.split(',')

        vol_0 = float( dataArray[0])
        cur_0 = float( dataArray[1])
        res_0 = float( dataArray[2])
        pow_0 = float( dataArray[3])
        Voltage_0.append(vol_0)
        Current_0.append(cur_0)
        ResInt_0.append(res_0)
        Power_0.append(pow_0)

        vol_1 = float( dataArray[4])
        cur_1 = float( dataArray[5])
        res_1 = float( dataArray[6])
        pow_1 = float( dataArray[7])
        Voltage_1.append(vol_1)
        Current_1.append(cur_1)
        ResInt_1.append(res_1)
        Power_1.append(pow_1)

        vol_4 = float( dataArray[8])
        cur_4 = float( dataArray[9])
        res_4 = float( dataArray[10])
        pow_4 = float( dataArray[11])
        Voltage_4.append(vol_4)
        Current_4.append(cur_4)
        ResInt_4.append(res_4)
        Power_4.append(pow_4)

        vol_5 = float( dataArray[12])
        cur_5 = float( dataArray[13])
        res_5 = float( dataArray[14])
        pow_5 = float( dataArray[15])
        Voltage_5.append(vol_5)
        Current_5.append(cur_5)
        ResInt_5.append(res_5)
        Power_5.append(pow_5)

        ArdTime = float( dataArray[16])

        PlotTime = PresentTime - timedelta(hours= h,minutes= m, seconds= s)
        Time.append(PlotTime)

        with open('AA_OUTPUT.csv', 'a') as f:
            if i==0:
                f.write('Time,Voltage_0 (V),Current_0 (mA), Internal Resistance_0 (mohm), Power_0 (mW),'
                    'Voltage_1 (V),Current_1 (mA), Internal Resistance_1 (mohm), Power_1 (mW),'
                    'Voltage_4 (V),Current_4 (mA), Internal Resistance_4 (mohm), Power_4 (mW),'
                    'Voltage_5 (V),Current_5 (mA), Internal Resistance_5 (mohm), Power_5 (mW)\n')
                f.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(ArdTime,
                    Voltage_0[-1],Current_0[-1],ResInt_0[-1],Power_0[-1],
                    Voltage_1[-1],Current_1[-1],ResInt_1[-1],Power_1[-1],
                    Voltage_4[-1],Current_4[-1],ResInt_4[-1],Power_4[-1],
                    Voltage_5[-1],Current_5[-1],ResInt_5[-1],Power_5[-1])) #for Python2 users
                i+=1
            else:
                #f.write(f'{PlotTime},{vol_0},{cur_0},{res_0},{pow_0},{vol_1},{cur_1},{res_1},
                    # {pow_1},{vol_4},{cur_4},{res_4},{pow_4},{vol_5},{cur_5},{res_5},{pow_5}\n') #for Python3 users
                f.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(ArdTime,
                    Voltage_0[-1],Current_0[-1],ResInt_0[-1],Power_0[-1],
                    Voltage_1[-1],Current_1[-1],ResInt_1[-1],Power_1[-1],
                    Voltage_4[-1],Current_4[-1],ResInt_4[-1],Power_4[-1],
                    Voltage_5[-1],Current_5[-1],ResInt_5[-1],Power_5[-1])) #for Python2 users
    drawnow(CreatePlot)
    plt.pause(0.0001)

is_open 来自 pySerial 模块可用于检索它的当前状态。

while True:
    if arduino.is_open:
        if arduino.in_waiting > 0:
            # rest of your code
        drawnow(CreatePlot)
        plt.pause(0.0001)
    else:
        arduino.open()