Reputation: 11
First post here.
I am trying to use Python to read data from a Lakeshore Model 218 Temperature Sensor, which uses an RS-232 port.
My diagnostic code:
import time
import serial
from serial.serialposix import Serial
print('starting')
#print(dir(serial.Serial))
print(dir(serial))
print('')
print(dir(Serial))
ser = serial.Serial(
port="COM3",
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.open()
ser.isOpen()
When I run the code, I get an error saying the computer can't find my port no matter what I list the port as.
Here's the specific error that appears below:
Traceback (most recent call last):
File "/Users/X/Desktop/cryostat/.venv/lib/python3.9/site-packages/serial/serialposix.py", line 322, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: 'COM3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/X/Desktop/cryostat/standardplot.py", line 13, in <module>
ser = serial.Serial(
File "/Users/X/Desktop/cryostat/.venv/lib/python3.9/site-packages/serial/serialutil.py", line 244, in __init__
self.open()
File "/Users/X/Desktop/cryostat/.venv/lib/python3.9/site-packages/serial/serialposix.py", line 325, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port COM3: [Errno 2] No such file or directory: 'COM3'
How do I locate and connect to the port?
Upvotes: 1
Views: 6045
Reputation: 11
I had a similar problem, list_ports finds EVERY possible port. I found that whenever I used list_ports, it would show both in use and disabled comports. I used the functions below to filter out any unusable ports before posting the options.
#Alphabetically lists the ports by name
def comslist():
ports = []
for i in serial.tools.list_ports.comports():
try:
ser = serial.Serial(i.name)
ser.close()
except serial.SerialException as e:
print(e)
else:
ports.append(i.name)
ports.sort()
return ports
#Finds the desired port using the name eg COM1
def selectcom(port):
try :
ser = serial.Serial(port)
except serial.SerialException as e:
print(e)
else:
return ser
Upvotes: 1
Reputation: 1148
Possibly, your device is on another COMx port (not COM3 as your code suggests). You could either check for the right COM port in the Device Manger on Windows or you could use the following python code snippet to find the open COM ports:
import serial.tools.list_ports as ports
com_ports = list(ports.comports()) # create a list of com ['COM1','COM2']
for i in com_ports:
print(i.device) # returns 'COMx'
Upvotes: 0