Having errors working with com ports using pyserial - python

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.

Related

cannot communicate Arduino with python

I am getting an error while trying to communicate Arduino with python, I am using Arduino module and I'm getting cannot open port error and I can communicate my Arduino from Arduino IDE.
from Arduino import Arduino
import time
board = Arduino(port="/dev/cu.usbmodem14201") # plugged in via USB, serial com at rate 115200
board.pinMode(13, "OUTPUT")
while True:
board.digitalWrite(13, "LOW")
time.sleep(1)
board.digitalWrite(13, "HIGH")
time.sleep(1)
This is my error
serial.serialutil.SerialException: [Errno 2] could not open port /dev/cu.usbmodem14201: [Errno 2] No such file or directory: '/dev/cu.usbmodem14201'
when I tried with pyfirmata I am getting an error
This is my code:
import pyfirmata
import time
board = pyfirmata.Arduino('/dev/cu.usbmodem14201')
led = board.get_pin('d:13:o')
while True:
led.write(1)
time.time(1)
led.write(0)
time.time(1)
my error for pyfirmata:
AttributeError: partially initialized module 'pyfirmata' has no attribute 'Arduino' (most likely due to a circular import)
To preface, I have done some Serial communication with Arduino, but have not worked with the Arduino library too extensively.
I suggest if you haven't done so already, considering the PySerial library. This may help with your initial issue with serial connection between your Mac and board. This does not entirely fix your need of directly writing to the LEDs, but can serve as a substitute in the meantime. You can use the incoming serial communication from your Mac to direct certain operations on your Arduino.
A great tutorial I have used can be found here:
https://create.arduino.cc/projecthub/ansh2919/serial-communication-between-python-and-arduino-e7cce0
Another issue may be that your Serial Monitor may be active which is blocking serial communication between devices over Python.

Python: File Can't be Found (pySerial)

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!

Com Port Permissions Python

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

how can i connect and send commands to a serial port while another program is using it?

I am using a telit he910g card. it is connected to my PC directly using a miniPCI slot.
I am using it for 3G internet connection and A-GPS/GPS services.
My system is running linux mint 17.1, the 3G connection is handled using the network manager APP and works great. The 3G connection is started and handled using a module that is part of a program I am writing.
The code I am using in order to connect to the serial port is this:
def _connect_to_device(self):
""" Connect to a serial port """
try:
self._device = serial.Serial(self._filename, baudrate=self._baud_rate)
except StandardError, e:
raise StandardError("Couldn't connect to GPS device. Error: %s" % str(e))
When I use the python program alone it works great. But when I try and use it while the 3G is on i cant connect to the serial device. The wierd thing is that if I try to connect to it using a program like "minicom" while 3G is turned on it DOES work.
So my question is: how can I make both run and work together? since now they are mutually exclusive.
thanks to all who help. :)
Glad you found a way round your problem. Just for completeness:
Normally, serial ports can be opened by multiple processes.
If one of them does ioctl(,TIOCEXCL) on the open file then further opens will return EBUSY until everyone closes the device. Only root can get past this and open the device at all times.
If root opens the device and does an ioctl(,TIOCNXCL), then other processes can open the device too.
In python, TIOCNXCL isnt defined anywhere, but you can do the ioctl (eg on stdin) with:
import fcntl
TIOCEXCL = 0x540c # from /usr/lib64/perl5/asm-generic/ioctls.ph
TIOCNXCL = 0x540d
print fcntl.ioctl(0, TIOCNXCL)
Ok, so it is solved.
the issue was that the telit module has 2 ports /dev/ttyACM0 (high speed) and /dev/ttyACM3 (lower speed).
I tried to connect to the high speed one, but apparently the 3G uses that one and it causes contentions.
So moving to use the lower speed port in my script solved the issue.

Python Serial Port - unable to write data

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.

Categories

Resources