使用python连续读取/监视串行端口(如果未连续打开端口,请运行脚本)

问题描述 投票:0回答:1

我是python和串行端口的新手。我想连续监视串口。如果未打开端口或拒绝访问,则需要不停运行python脚本。我做了些什么,但是当PORT未打开或访问被拒绝时,该脚本已停止。请帮助某人解决此问题。

import serial
z1baudrate = 9600
z1port = 'COM4'
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
try:
   if z1serial.is_open:
      while True:           
        size = z1serial.inWaiting()                   
        if size:                
            data = z1serial.read(size)                                                  
            res= data.decode("utf-8")   
            print(res)      
        else:
            print("Data not reading")
       time.sleep(1)
  else:
    z1serial.close()
    print('z1serial not open or Already in use')
except serial.SerialException as e:
  z1serial.close()
  print('COM4 not open')
python pyserial
1个回答
0
投票

您需要在z1serial块中包含try分配为

import serial
import time
z1baudrate = 9600
z1port = 'COM4'
while True:
    try:
        z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
        if z1serial.is_open:
            while True:           
                size = z1serial.inWaiting()                   
                if size:                
                    data = z1serial.read(size)                                                  
                    res= data.decode("utf-8")   
                    print(res)      
                else:
                    print("Data not reading")
                time.sleep(1)
        else:
            z1serial.close()
            print('z1serial not open or Already in use')
    except serial.SerialException:
        print('COM4 not open')
        time.sleep(1)

这对我有用,在Python 3.7上运行

© www.soinside.com 2019 - 2024. All rights reserved.