I am trying to run 2 very basic test scripts, a read script and a write test script over serial communication using loopback. I have the read script in a while loop to read bytes received. I have the write script sending a single byte whenever I run it. The issue I am running into is I am trying to setup communication over a Virtual serial port set to COM5 using loopback. The read script connects and opens the port and the write script attempts to write through that port to the read script. But when I run the write script it gives me this error:
serial.serialutil.SerialException: could not open port 'COM5': PermissionError(13, 'Access is denied.', None, 5)
I have tried to disable and re-enable the port through Device Manager, I’ve tried restarting the Virtual serial port driver(VSPD) and have tried restarting my computer. I can monitor the opening and closing of the serial port through the VSPD and it is opening and closing correctly. It is also receiving the bytes when I run the write script when the read script is not active. Below I have put my code and the VSPD setup, the top comment describes on the code if it is either the read or the write script:
# Serial write Script
import serial
# Configure the serial port
ser = serial.Serial(
port='COM5',
baudrate=9600,
bytesize=serial.EIGHTBITS, # 8 bits per byte
parity=serial.PARITY_NONE, # No parity
stopbits=serial.STOPBITS_ONE, # 1 stop bit
timeout=0.5 # Timeout in seconds
)
# Send a byte
byte_to_send = b'x41' # Example byte to send (here, ASCII 'A')
ser.write(byte_to_send)
print(f"Sent byte: {byte_to_send}")
# Close the serial port
ser.close()
#Serial read script
import serial
import time
# Configure the serial port
ser = serial.Serial(
port='COM5',
baudrate=9600,
bytesize=serial.EIGHTBITS, # 8 bits per byte
parity=serial.PARITY_NONE, # No parity
stopbits=serial.STOPBITS_ONE, # 1 stop bit
timeout=0.5 # Timeout in seconds
)
try:
while True:
# Read a byte
byte_received = ser.read(1) # Read one byte
print(f"Received byte: {byte_received}")
# Optional: Add a small delay to reduce CPU usage
time.sleep(0.1) # Adjust as needed
except KeyboardInterrupt:
print("Interrupted")
finally:
# Ensure the serial port is properly closed
if ser.is_open:
ser.close()
print("Serial port closed")
Fisch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
the serial ports cannot be the same if you are trying to use 2 different scripts, since a loopback needs the port to be open to send a receive data it cannot be closed and re-opened in another script. It needs to be 2 different serial ports that are linked together, one that is held open on the receiver end and a sender that is opened and sends data to the receiver
Fisch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.