简体   繁体   English

使用Python和pyserial访问USB串口

[英]Access USB serial ports using Python and pyserial

How do I access the USB port using pyserial?如何使用pyserial访问USB端口? I have seen an example with:我见过一个例子

import serial

ser = serial.Serial('/dev/ttyUSB0')

I used to access the serial port from MATLAB on Windows and using the appropriate syntax, /dev/ttyUSB0 would be replaced by COM1 or any other COM port.我曾经从 Windows 上的 MATLAB 访问串行端口并使用适当的语法, /dev/ttyUSB0将被COM1或任何其他 COM 端口替换。

I'm on a Mac and I tried using the serial port scanners on the pyserial documentation to no avail.我在 Mac 上,尝试使用pyserial文档中的串行端口扫描仪无济于事。 I think I should write it like this:我想我应该这样写:

import serial

name = ? # Names of serial ports on Mac OS X
ser = serial.Serial(name)

How do I find out what name should be on a Mac?我如何找出 Mac 上的name

EDIT: In response to an answer below, I'd like to find out how to access both USB to RS232 converters as well as pure USB ports.编辑:针对下面的回答,我想了解如何访问 USB 到 RS232 转换器以及纯 USB 端口。

You can only access USB Serial Adapters using pyserial (ie, USB RS-232 dongles).您只能使用 pyserial 访问 USB 串行适配器(即 USB RS-232 加密狗)。 If you want generic USB access you should be looking into "libusb".如果您想要通用 USB 访问权限,您应该查看“libusb”。 If it is RS-232 you are trying to access through USB then you should look for a file in /dev starting with cu.usb* (/dev/cu.usbserial-181 for example).如果您尝试通过 USB 访问的是 RS-232,那么您应该在 /dev 中查找以 cu.usb* 开头的文件(例如 /dev/cu.usbserial-181)。

To find the available ports you can use serial.tools (which is part of the pyserial library, but needs to be imported separately).要查找可用端口,您可以使用serial.tools (它是pyserial库的一部分,但需要单独导入)。 The device name can then be found using the .device method.然后可以使用.device方法找到设备名称。 This works for me on Mac:这在 Mac 上对我有用:

from serial.tools import list_ports
port = list(list_ports.comports())
for p in port:
    print(p.device)

For more on list_ports , see: https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports有关list_ports的更多信息,请参阅: https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM