Working on trying to get serial comminications working between an arduino and my computer. When working off the code that can be seen here I keep getting this error:
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': WindowsError(5, 'Access is denied.')
I have edited the com port used in the aformentioned code to match what I am actually using, but I cant get this error to go away. Here are a few thinks I've tried:
Ran file as administrator
Started pycharm as administrator
Changed the security properties for the directory the program is in
Unistalled and reinstalled the COM port in device manager
Restarted Computer
The weird thing is sometimes after I do these fixes it will work once, and then when I stop the program and start it again it once again throws the error.
Ran into the same problem before and I realized that I left the serial connection open after serial read program execution completed. Closing the serial connection once done should work.
import serial
serial = serial.Serial('COM124', baudrate=115200, timeout=1)
#Main function to do something
my_function():
...
#end of Main function
my_function()
#adding below line will solve your problem
serial.close()
Related
Having a small problem with opening a serial/console port via pySerial.
My program is meant to get the active com port, open a console connection and then send data. When the program is running and I plug in my RS232 USB I receive a SerialException error. (More specifically, "Could not open port: FileNotFoundError")
In the event where the program is run, it will keep printing "No RS232 Connected", but when the RS232 USB is connected the program breaks and runs into the SerialException error.
If I plug in the RS232 USB before running the program and then run it, it reads and performs normal operation without issue.
ports = serial.tools.list_ports.comports(include_links=False)
if not ports:
print("No RS232 Connected")
if ports:
for port in ports:
print('Found port ' + port.device)
ser = serial.Serial(port.device)
if ser.isOpen():
ser.close()
break
console = serial.Serial(port.device, baudrate=9600, parity="N", stopbits=1, bytesize=8, timeout=0.4)
I am quite new to Python and programming in general, but I feel that the problem may be around the 'ports' list already being populated twice due to the while True loop. Then when we go to create the console by opening the port we are expecting one entry in the list, but there are two.
Since we can't have 2 open console connections on the same COM port, we receive the error.
If I print the 'ports' list I get this.
"[<serial.tools.list_ports_common.ListPortInfo object at 0x000002B5D77F0D68>]
[<serial.tools.list_ports_common.ListPortInfo object at 0x000002B5D77F0D68>]"
Any help would be greatly appreciated! Please let me know if you require any more details.
Thanks,
After further research into it, I have realised that when a RS232 USB is plugged into the PC, we need to give it a bit of time to open a stream. It sounds like it is opened when the temp file is created for it.
Although it was identifying that a COM port was available almost immediately, it was not ready by the time I was trying to create the Serial instance, which was why I was getting the FileNotFound error.
A simple sleep function of half a second has solved the issue!
I am trying to interface with my com ports, specifically an XBee connected to thi using this code.
from xbee import XBee
from serial import Serial
PORT = 'COM3'
BAUD = 9600
ser = Serial(PORT, BAUD)
xbee = XBee(ser)
# Send the string 'Hello World' to the module with MY set to 1
xbee.tx(dest_addr='\x00\x01', data='Hello World')
# Wait for and get the response
print(xbee.wait_read_frame())
ser.close()
However, this error keeps arising.
SerialException: could not open port 'COM3': WindowsError(5, 'Access is denied.'). It goes away when I restart my computer, buts it keeps returning. I'd prefer to understand why its happening so I don't need to keep restarting my computer. Would really appreciate any help, thanks. I am working through the IDLE interface with python 2.7 just in case that is relevant.
A serial port can be "open" in only one application at a time. Once application "A" opens the port, application "B" will get an Access Denied error when it tries to open the same port. In your case, you need to figure out what other application is holding the port and close it first.
I've got a python script that basically looks something like this:
#############################
# MAIN LOOP
while True:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client_socket.connect((url, socketnum))
packet = somedata
client_socket.sendall(packet)
except Exception as e:
# an error occurred
logging.error("An error occurred: {}".format(e))
pass
finally:
logging.info("Closing socket...")
client_socket.close()
time.sleep(70)
What I find is that if this script is run before an internet connection is established on the computer (an embedded Linux system), naturally, when the socket tries to connect, I get "Errno -3 Temporary failure in name resolution". However, if the internet connection is then established, the program STILL cannot resolve the hostname - the only way to get it to work is to restart the python script.
Since this system is not one where I can guarantee the presence of an internet connection at all times, is there anyway to get python to realise that the internet connection now exists and that name resolution information is now available?
EDIT: Some further testing shows that this only happens if the python program is started before any successful internet connection is established on the machine after a boot up. If the python program is started AFTER an internet connection has previously been established on the machine (even if it's subsequently been disconnected), the program operates correctly and will successfully connect to the internet after internet connectivity is restored.
So:
Bootup->Python started->Internet connection established = program doesn't work
Bootup->Internet connection established->Internet disconnected->Python started = program works fine.
Try flushing DNS cache in every iteration.
import os
...
while True:
os.popen('nscd -I hosts',"r")
...
or try service nscd restart command instead.
I am new to python and am trying to run a prewritten program but keep recieving an error here is the whole error.
Traceback (most recent call last):
File "C:\source\python\pill.py", line 29, in <module>
ser.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
SerialException: could not open port 'COM7': WindowsError(5, 'Access is denied.')
I am the admin as well
You may have another program using the COM port, for example a test program like firmata_test.exe that our course work told use to use.
One course module told us to run that program, which is a Windows executable that opens the COM port and monitors the various pins on the board and lets us toggle their state High or Low. The next module told us to run some Python code in the IDLE code editor that would connect to the board and write to the pin state to turn an LED on and off. The Python code failed with the Access is denied message, because the COM port was already in use by firmata_test.exe, though the error message did not mention this specifically (because the Python code did not know why it could not open the port, only that it could not).
Close any other software such as firmata_test.exe that may be using the COM port and run your Python code again.
I am relatively new to Python. I wrote a script and need to add triggers that need to be send via an usb serial port to another pc. The problem is that the triggers (in this code example the 2) never show up on the software on the other pc. When I check it with the print() command, it does print a value, but the printed value is the same number for two different triggers. I have read other posts, I searched the internet, and I tried various things, but I didn't manage to resolve this iusse. This is the code I use for interfacing with the serial port (COM3).
#this part of code is defined at the beginning:
import serial
ser = serial.Serial(port=2, baudrate=9600)
ser.close()
#this part of the code later on to interface with the serial port:
ser.open()
ser.write(chr(2))
ser.close()
Maybe anyone here has any suggestions on where the problem could be? Thanks!
If you haven't already, check that the port settings are correct, 9600,8,N,1 for example. These must match the settings of the remote serial port.
It might be useful to check that the serial connection does work with a terminal emulation program such as minicom (linux), or PuTTY (Windows). Once you have verified that a connection can be made and data transferred, you can be certain that you are connecting to the correct local port, that the port settings are correct, and that your serial cable is working properly.