14

How do I access the USB port using pyserial? 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.

I'm on a Mac and I tried using the serial port scanners on the pyserial documentation to no avail. 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?

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.

Community
  • 1
  • 1
Kit
  • 30,365
  • 39
  • 105
  • 149

2 Answers2

9

You can only access USB Serial Adapters using pyserial (i.e., USB RS-232 dongles). If you want generic USB access you should be looking into "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).

Majenko
  • 1,816
  • 18
  • 27
  • Even while using Houdini to display hidden files and folders, `/dev` is a symbolic link without anything inside. I tried using Finder's Go to Folder and I'd get "The folder can't be found". How do I get around this? – Kit Jun 11 '11 at 14:46
  • 2
    try `ls -l /dev/cu.usb*` from a terminal window – Majenko Jun 11 '11 at 14:47
  • Nothing like `cu.usb` at all. I do find `cu.Kit-COM1`, and only that. But the Macbook Pro has two USB ports on the left side (and possible more hidden ones used by the keyboard and other built-ins). – Kit Jun 11 '11 at 14:54
  • Only USB ports that have an RS-232 adapter plugged in will appear as /dev/cu.whatever (that is the cu.Kit-COM1 in your case). USB is *not* serial in the traditional sense of the word. It is far more high-tech than that. – Majenko Jun 11 '11 at 16:00
2

To find the available ports you can use serial.tools (which is part of the pyserial library, but needs to be imported separately). The device name can then be found using the .device method. This works for me on 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