0

Im newbie for python and serial port. I want to monitor serial port continuously. If port not opened or access denied, need to run the python script without stop. I had done something, But that script has stopped when the PORT not opened or access denied. kindly, help someone to close this issue.

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')

1 Answers1

0

You need to include the z1serial assignment inside the try block as

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)

This worked for me, running on Python 3.7

Romain F
  • 397
  • 6
  • 14
  • if i include the z1serial assignment inside the try block,port not open means script has stopped.But, i want to keep on watching the port until open.What to do. – Abdul Rahman B Feb 09 '20 at 13:22
  • I modified a little bit the code. I included an infinite loop so you keep watching at the port until it is open. I also included a `time.sleep(1)` if the port is not open to let some delay between checking the port, but you can change the delay. Does this answer your issue? – Romain F Feb 09 '20 at 16:04