I am trying to implement data sending in Python 3 on a raspberryPi (as a part of a bigger project) and cannot receive data when I connect the Rx and Tx pins. Regardless of using Python 2 or 3 (as far as I understand this API allows Python 3 programming) I either get Received: b'\n' response or such an exception:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 471, in write
n = os.write(self.fd, d)
OSError: [Errno 5] Input/output error
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./uart.py", line 12, in <module>
port.write(bytearray(input_data, 'utf-8'))
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 485, in write
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 5] Input/output error
I can't write anything except from buffered reader though.
The code I've made is here:
#!/usr/bin/env python3
import serial
port = serial.Serial("/dev/ttyAMA0", baudrate=9600)
while True:
input_data = input("Say sth: ")
if input_data != 'exit':
port.write(bytearray(input_data, 'utf-8'))
print('Sent: {0}'.format(bytearray(input_data, 'ASCII')))
output_data = port.readline()
print('Received: {0}\n'.format(str(output_data)))
else:
break
port.close()
I want to use ASCII encoding since it will be further connected to an microcontroller with code in C. I've also checked whether any data is written into the buffer (and it is), I've tried out laying the programme to sleep for a second after sending data, I've tried using port.read(port.inWaiting()) and port.read(in_waiting) (no attribute found in the latter case) and nothing seems to be helpful.
I've also tried this example; I am sure correct pins are connected and I have updated and upgraded my raspbian by using sudo apt-get update and sudo apt-get upgrade and when I typed sudo apt-get install python3-serial I was told that I already have newest version installed.
I am posting this answear to close the topic and to help anyone who might come across similar difficulties.
Since the processor is of different architecture trying to set up ports with setserial was pointles, however this was exactly the problem.
pi#raspberrypi ~ $ sudo setserial -g /dev/ttyAMA0
/dev/ttyAMA0, UART: undefined, Port: 0x0000, IRQ: 83
The answear I found here solved all the problems.
Related
new to Python but it really makes fun to work with :-)
Using the pyserial lib and works fine so far. BUT...
...is there a way to ignore the following problem: During a serial communication I disconnect the COM-cable for a short time. I got the following errormessage then:
**Traceback (most recent call last):
File "C:\Users\greulich\PycharmProjects\arduino_serial\main.py", line 48, in <module>
functions.receiveWithStartMarkers()
File "C:\Users\greulich\PycharmProjects\arduino_serial\functions.py", line 30, in receiveWithStartMarkers
receivedChar = serialPort.read(1) # read 1 byte
File "C:\Users\greulich\PycharmProjects\arduino_serial\venv\lib\site-packages\serial\serialwin32.py", line 275, in read
raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
serial.serialutil.SerialException: ClearCommError failed (PermissionError(13, 'Das Gerät erkennt den Befehl nicht.', None, 22))**
My code looks like that:
while serialPort.is_open is True and newData is False:
#try:
receivedChar = serialPort.read(1) # read 1 byte
print(str(date.time()) + ' >>> ' + 'I got the following byte: ' + str(receivedChar))
I opened up port initially in that module:
try:
serialPort = serial.Serial('COM12', 115200)
except:
print('COM-Port not available!')
print('Will exit not the Python program!')
exit() #quits the complete Python program
serialPort.timeout = 3
Is there a way to define kind of a timeout until this error will hit me where the user has the chance to reconnect the cable?
In a nutshell: I want to be able to disconnect the com cable for a short time and connect it again without an error showing :-)
Thanks,
Markus
I am trying to connect JRC JJ1000 drone using dronekit + python.
when executing the connect command:
dronekit.connect('com3', baud=115200, heartbeat_timeout=30)
I am getting the following error:
ERROR:dronekit.mavlink:Exception in MAVLink input loop
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\dronekit\mavlink.py", line 211, in mavlink_thread_in
fn(self)
File "C:\Python37\lib\site-packages\dronekit\__init__.py", line 1371, in listener
self._heartbeat_error)
dronekit.APIException: No heartbeat in 5 seconds, aborting.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python37\lib\site-packages\dronekit\__init__.py", line 3166, in connect
vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout)
File "C:\Python37\lib\site-packages\dronekit\__init__.py", line 2275, in initialize
raise APIException('Timeout in initializing connection.')
dronekit.APIException: Timeout in initializing connection.
I left no store unturned but no progress. I also tried both Python 2.7 and 3.7 with same result.
I have been getting the same error. I am using some custom code in a docker container to run simulations with dronekit and ArduPilot. The error is intermittent. So far it seems like the only way to get the error to stop is to:
Close all docker containers.
Open windows task manager and wait for vmmem to lower memory usage (5-10m).
Try again.
Maybe the problems are related somehow. To me it seems like the connection might be in use by a previous instance and it was not properly close. Since waiting for vmmem to free up resources appears to fix it. I would prefer a better solution if anyone finds one!
We are using python code like this to connect:
from dronekit import connect
...
# try to connect 5 times
while connected == False and fails < 5:
try:
vehicle = connect(connection_string, wait_ready=True)
except:
fails += 1
time.sleep(3)
print("Failed to connect to local mavlink sleeping for 3 seconds")
else:
connected = True
Where the connection_string is of the form:
"tcp:host:port"
Also, the documentation states "If the baud rate is not set correctly, connect may fail with a timeout error. It is best to set the baud rate explicitly." Are you sure that you have the correct baud rate?
I am using Cambrionix PowerPad15s for my devices but while running their first code which is to find all the device connected to the usb i am having some issue in jsonrpc file(Which is provided by the company itself).
I have to import this-
from cbrxapi import cbrxapi
This code is to get all the connected device in the usb port and save in result variable-
result = cbrxapi.cbrx_discover("local")
Rest of the code is-
if result==False:
print "No Cambrionix unit found."
sys.exit(0)
unitId = result[0]
handle = cbrxapi.cbrx_connection_open(unitId)
nrOfPorts = cbrxapi.cbrx_connection_get(handle, "nrOfPorts")
cbrxapi.cbrx_connection_close(handle)
print "The Cambrionix unit " + unitId + " has " + str(nrOfPorts) + " ports."
The error I am facing in is
Traceback (most recent call last):
File "cbrx_api_quickstart.py", line 9, in
result = cbrxapi.cbrx_discover("local")
File "/usr/local/share/cbrxapi/jsonrpc-0.1/jsonrpc.py", line 936, in call
return self.__req(self.__name, args, kwargs)
File "/usr/local/share/cbrxapi/jsonrpc-0.1/jsonrpc.py", line 908, in __req
raise RPCTransportError(err)
jsonrpc.RPCTransportError: [Errno 111] Connection refused
The product I am using is Cambrionix
Sorry for not explaining properly. I am still in learning phase..
Found the solution-
I have to install one more file to my system to get the code working..
$ sudo apt-get install avahi-daemon
And I need to ensure that one more script is running on my system.
install_service.sh in /usr/local/share/cbrxd/setup
I am able to run scripts with Python 2.6.6 that open the serial port and exchange data bidirectionally. After installing both Python 2.7 and 3.5, needed for objects that cannot be executed in 2.6, I receive the same error (IOError: [Errno 110] Connection timed out).
I installed both 2.7 and 3.5 using (make altinstall) followed by (easy_install-2.7 -U pyserial) and (easy_install-3.5 -U pyserial).
Does anyone have a good guess as to why 2.6 will open the port and pass data, but both 2.7 and 3.5 fail?
I am running on CentOS 6.8, Kernel Linux 2.6.32-642.11.1.el6.x86_64 and using a USB to DB9 serial cable without any issues in 2.6.
python stest.py
Hello World from serial port running under Python 2.6.6.
python2.7 stest.py
Traceback (most recent call last):
File "stest.py", line 3, in <module>
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=False,dsrdtr=False)
File "build/bdist.linux-x86_64/egg/serial/serialutil.py", line 182, in __init__
File "build/bdist.linux-x86_64/egg/serial/serialposix.py", line 267, in open
File "build/bdist.linux-x86_64/egg/serial/serialposix.py", line 588, in _update_rts_state
IOError: [Errno 110] Connection timed out
python3.5 stest.py
Traceback (most recent call last):
File "stest.py", line 3, in <module>
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=False,dsrdtr=False)
File "/usr/local/lib/python3.5/site-packages/pyserial-3.2.1-py3.5.egg/serial/serialutil.py", line 236, in __init__
File "/usr/local/lib/python3.5/site-packages/pyserial-3.2.1-py3.5.egg/serial/serialposix.py", line 288, in open
File "/usr/local/lib/python3.5/site-packages/pyserial-3.2.1-py3.5.egg/serial/serialposix.py", line 605, in _update_rts_state
TimeoutError: [Errno 110] Connection timed out
The stest.py script:
import serial
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=False,dsrdtr=False)
ser.write("Hello from CentOS box.");
while True:
chunk = ser.read(128)
if(chunk != ''):
print(chunk + '\n')
ser.close()
As suggested earlier, I did try to open the port several times. I had read that may be an issue from other posts. I also increased the timeout from 0 to 5. Still no joy. Here is that version (assuming I understood the way to make the multiple attempts):
import serial
ser = 0
for i in range (1, 20):
print("Attempt" + str(i))
try:
ser = serial.Serial(port='/dev/ttyUSB0',timeout=5,xonxoff=False,rtscts=False,dsrdtr=False)
if(ser):
break
except:
print("Failed")
ser.write("Hello from CentOS");
while True:
chunk = ser.read(24)
if(chunk != ''):
print(chunk + '\n')
ser.close()
I think this may be kernel related. I was able to exchange data by changing the rtscts value from False to 1. Unfortunately, this does not help my end goal since the remote device is 3-wire and does not support handshaking (RTS/CTS). So, I am still without a solution. The question now is:
Why does the (rtscts value of False) fail in 2.7 and 3.5, but work in 2.6.6?
The working code (but not usable to me because my equip does not handshake):
#!/usr/bin/python3.5
import serial
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=1,dsrdtr=False)
ser.write(b"Hello from CentOS");
while True:
chunk = ser.read(24)
if(chunk):
print(str(chunk) + '\n')
ser.close()
Adding to the evolution of my discovery, it is indeed an issue in the compatibility of CentOS 6.8 and pyserial's serialutil.py and serialposix.py. I can open a serial port and read/write data just fine with rtscts = 1. If I reconfigure the port during run time and set rtscts to False, 2.6.6 handles it well. Pythons 2.7 and 3.5 immediately issue errors and abort displaying the same ([Errno 110]) error shown at the beginning of my post. Here is the code if others would care to replicate. Preferably CentOS users since this is likely OS related.
import serial
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=1,dsrdtr=False)
# Python 2.6.6, 2.7, and 3.5 will send this following string.
ser.write(b"Hello from CentOS");
# Python 2.7 and 3.5 error-out after this change, but system Python (2.6.6) is okay.
ser.rts = False
while True:
chunk = ser.read(24)
if(chunk):
print(str(chunk) + '\n')
ser.close()
Any suggestions on next steps? Am I just out of luck?
I have seen simple code in stackoverflow using pyserial in USB ports with Python 3.3 but I can't get this to work on my new installation of pyserial 2.7 [in Windows 7, 64 bit, with 3 USB ports]. Installation of pyserial went smoothly, I can import without error and methods are recognized in the Pyscripter IDE which boosts confidence in a good installation, however:
The code stripped down to its error producing essentials is:
import serial
def main():
ser = serial.Serial(port='COM2')
ser.close()
if __name__ == '__main__':
main
From this I receive a dialog box with the error "SerialException: could not open port 'COM2': FileNotFoundError(2,'The system cannot find the file specified.',None,2)"
The Traceback states:
*** Remote Interpreter Reinitialized ***
>>>
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "C:\Python33\Lib\site-packages\scanport2.py", line 19, in <module>
main()
File "C:\Python33\Lib\site-packages\scanport2.py", line 15, in main
ser = serial.Serial(port='COM2')
File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python33\Lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM2': FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)
And the code segment in the imported module which raises the SerialException is:
# the "\\.\COMx" format is required for devices other than COM1-COM8
# not all versions of windows seem to support this properly
# so that the first few ports are used with the DOS device name
port = self.portstr
try:
if port.upper().startswith('COM') and int(port[3:]) > 8:
port = '\\\\.\\' + port
except ValueError:
# for like COMnotanumber
pass
self.hComPort = win32.CreateFile(port,
win32.GENERIC_READ | win32.GENERIC_WRITE,
0, # exclusive access
None, # no security
win32.OPEN_EXISTING,
win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
0)
if self.hComPort == win32.INVALID_HANDLE_VALUE:
self.hComPort = None # 'cause __del__ is called anyway
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
I do have an active device connected to COM2 as identified in the Windows device manager. I also have tried scanning all the ports, but the code stops on the first use of serial.Serial
This appears that something may be going on with win32?
I am a newbie for interfacing Python with hardware.
I would try the following:
Unplug and replug the device.
Reboot.
Run WinObj and look in the GLOBAL?? folder; you should see COM2 there as a symbolic link to something more driver-specific.
What type of device do you have connected to COM2? If it uses usbser.sys, you might have better luck substituting \\.\USBSER000 for COM2 in your code, but remember to escape those backslashes properly.
On some machines there are strange problems with low COM port numbers that I can't explain. Try reassigning the device to COM6 in the Device Manager.
It looks like the pyserial download page only contains links for 32 bit python? This unofficial page seems to have links for 64 bit installations, however be cautious installing from unknown sources.
This answer also suggests installing it using pip: https://stackoverflow.com/a/8491164/66349