Serial Ports Linux vs Windows

人走茶凉 提交于 2019-12-13 03:59:40

问题


I am having issues with my pyserial program on Ubuntu 16. I am trying to send a break command to a hardware device using pyserial. I wrote a python script that:

  1. Sets the port/baud/parity/bytesize/...
  2. Opens the port
  3. Sends a break command
  4. Reads the return message from the device.

I run the script on my Ubuntu 16.04 machine and I get zero response, it just hangs or eventually timeouts. I copy the same script to my Windows machine, change the port (from /dev/ttyUSB0 to COM#) and my script works perfectly, gets a response from the device immediately.

When I run the script on Ubunutu I have to give permissions to the port (sudo chmod 666 /dev/ttyUSB), or I get permission denied errors when opening the port. Not sure if this matters.

Does anyone have any insight on what might be going on? I know Windows and Linux handle serial/com ports differently but I am a newbie to both Linux and serial so not sure if I am missing something.

I am using this USB to Serial cable (http://www.ugreen.com.cn/product-681-en.html) and I had to install some drivers. I connected the serial read/write pins and tested to make sure data is going through (which it is) so I know that works.

import serial
ser = serial.Serial()
ser.port = '/dev/ttyUSB0' # or COM12 on windows
ser.baudrate = 9600
ser.parity = serial.PARITY_NONE
ser.bytesize = serial.EIGHTBITS
ser.stopbits = serial.STOPBITS_ONE
ser.open()
ser.send_break(duration=0.9)
print(ser.read(10))

回答1:


First off, you need to have proper permissions for accessing serial ports. It can be done by including your user into the group dialout:

sudo usermod -aG dialout <user>

You need to restart the system to complete it.

To avoid of some information to remain in buffers, you may need to clear read and write buffers before serial port operations:

pyserial 3.0:

ser.reset_input_buffer()
ser.reset_output_buffer()

pyserial 2.7 or earlier:

ser.flushInput()
ser.flushOutput()

Don't forget to close a port after all operations being done. Hope this helps.




回答2:


First forget about your app and focus on the port troubleshooting, use putty in serial mode for sending a few terminal chars using this port. Use a jumper for conecting DB9 pin 3 to pin 2(rx and tx) an validate that you receive an echo of each character you type.



来源:https://stackoverflow.com/questions/49957705/serial-ports-linux-vs-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!