How to open serial port in linux without changing any pin?
Just to clarify — in Linux at least, calling open(«/dev/ttyUSB0», os.RDWR) makes both the RTS and the DTR lines go up in the serial port. After the port has been opened, RTS can be set to low again by calling ioctl. However, the question is — how to open the device without setting RTS high even momentarily?
stty requires redirecting the output to the terminal to have any effects (obviously) and doing stty clocal > /dev/ttyUSB0 obviously opens the serial port before doing the action. So, stty will also cause the RTS line to go high, atleast momentarily.
4 Answers 4
I have no idea why you’d want to do this, but this can be done pretty easily by modifying the linux kernel driver for your serial console so it doesn’t toggle RTS. For example, for the 8250-series driver in drivers/tty/serial/8250/ you could change every write to the MCR register (UART_MCR) to ensure that bit 1 (mask is UART_MCR_RTS) is never set.
Since it’s abstracted away in userspace, you’re out of luck if you want to do this without modifying the kernel driver.
«I have no idea why you’d want to do this» -> it’s very common for embedded bootloaders to have RTS connected to the reset pin and DTR connected to the bootloader select pin (or vice versa). If the reset pin is toggled, even for a fraction of a microsecond, the chip will reset. This means that it isn’t easy to use the control lines for this purpose if you’re also using the serial port for general communication with the device. not without disconnecting the control lines first 🙁
I see, it’s sort of hijacking the control flow line to reset into a programming state right before serial data is sent. Convenient, at least until design changes from having a tiny microcontroller to use a quad-core SoC running Linux and the hardware engineer doesn’t bother to consult anyone on changes required to the programming model.
@cha5on Yeah, it’s definitely a hack, better to have a real upload protocol that doesn’t interfere with the serial lines, unfortunately in the real world many devices just expose a USB port with a serial interface behind that does just that, so you need to either work with that or spend time modding the device (or throw it away).
Having the same problem, I’d give it a try by patching the ftdi_sio kernel driver. You just need to uncomment a small piece of code in ftdi_dtr_rts() like this:
static void ftdi_dtr_rts(struct usb_serial_port *port, int on) < . /* drop RTS and DTR */ if (on) set_mctrl(port, TIOCM_DTR /*| TIOCM_RTS*/); //and the RTS handshake line is not longer changed upon open() call. Note, that the uart than might not longer working with RTS/CTS hardware handshake, as long as your modified kernel driver is loaded. But you can still control the state of the RTS handshake line manually by calling e.g.:
int opins = TIOCM_RTS; ioctl(tty_fd, TIOCMBIC, &opins);
I'd tested this with the Ctrl+A+G command of picocom 2.3a, running Kubuntu 16.04 64 bit and Ftdi FT2232H based usb uart adapter.
You might find more details on this topic here.
Checking picocom.c, it uses O_NONBLOCK : tty_fd = open(opts.port, O_RDWR | O_NONBLOCK | O_NOCTTY); and it behaves as described above.
A change in the DTR pin can be (eventually) avoided using the command line
This has the effect of making DTR turn on; and subsequently when the port is opened and closed, DTR is not affected.
And there is code there to do the same thing from python via termios , this can be done before opening the port via pyserial:
import termios path = '/dev/ttyACM0' # Disable reset after hangup with open(path) as f: attrs = termios.tcgetattr(f) attrs[2] = attrs[2] & ~termios.HUPCL termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
The OP was running this on a Raspberry Pi, but I just tried it on Linux Mint on x86_64, it worked. I don't know how RTS is affected.
The reason I find this useful, is for communication with an Arduino Nano - which has a USB-> serial chip on board - and normally the Arduino gets reset every time you open the serial port from linux (rising edge of DTR causes reset). For some applications, this is not a problem, but it's clearly useful to avoid this for other applications, and it's not so easy to remove that tiny capacitor from the Arduino which connects DTR to reset.
You will still get a single reset when the stty command is executed (after plugging in the USB cable). But at least you can then keep opening and closing the serial port after that without further resets.
Открыть ком порт linux
Когда Wine запускается, последовательные и параллельные порты определяются автоматически. Windows именует свои последовательные порты как COM, за которым идет номер, например COM1, COM2, и т. д. Подобным образом параллельные порты получают в Windows имя LPT с номером, как например LPT1. Linux, Mac и BSD имеют свои принципы назначения имен устройствам, но в каждом случае последовательные или параллельные порты размещаются в виде файлов нулевого размера в каталоге /dev. Вы можете увидеть отображение устройств Windows на устройства Unix, если просмотрите ~/.wine/dosdevices.
$ ls -l ~/.wine/dosdevices/ total 0 lrwxrwxrwx 1 alex alex 10 May 13 21:21 c: -> ../drive_c lrwxrwxrwx 1 alex alex 10 May 14 14:43 com1 -> /dev/ttyS0 lrwxrwxrwx 1 alex alex 10 May 14 14:43 com2 -> /dev/ttyS1 lrwxrwxrwx 1 alex alex 10 May 14 14:43 com3 -> /dev/ttyS2 lrwxrwxrwx 1 alex alex 10 May 14 14:43 com4 -> /dev/ttyS3 lrwxrwxrwx 1 alex alex 12 May 14 14:43 com5 -> /dev/ttyUSB0 lrwxrwxrwx 1 alex alex 8 May 13 21:22 d:: -> /dev/sr0 lrwxrwxrwx 1 alex alex 8 May 14 14:43 lpt1 -> /dev/lp0 lrwxrwxrwx 1 alex alex 1 May 13 21:21 z: -> /
Убедитесь, что имеете достаточно прав для доступа к вашим последовательным и параллельным портам. На Linux пользователь должен быть членом группы sys или dialout, чтобы он мог получить доступ к последовательным портам, или членом группы lp для доступа к параллельным портам.
Чтобы поменять отображение устройств Wine по умолчанию, запустите wine regedit , и создайте строковые записи в HKEY_LOCAL_MACHINE\Software\Wine\Ports , где имя записи это имя устройства Windows, и значение записи это путь до устройства системы Unix. Если рассмотреть пример выше, то чтобы сделать COM1 соответствующим первому подключенному преобразователю USB-serial, создайте запись с именем COM1 и значением /dev/ttyUSB0. Также вы можете захотеть создать запись с именем COM5 без значения, чтобы удалить устройство COM5, которое теперь дублирует COM1. После редактирования реестра выгрузите Wine командой wineserver -k , и в следующий раз, когда Wine запустит программу, сделанные вами изменения вступят в силу.
Как добавить пользователя в группу sys:
$ sudo usermod -a -G sys имяпользователя $ grep sys: /etc/group sys:x:3:имяпользователя
Перезагрузите компьютер, чтобы изменения вступили в силу.
1. Serial and Parallel Ports site:wiki.winehq.org.
How to connect to a serial port on Linux
Question: I need to access the management terminal of a hardware switch/router (e.g., Cisco Catalyst or HP ProCurve) via its console port. The switch console port is connected to the serial port of my Linux box. How can I connect to the serial port from a Linux terminal?
First of all, let's assume that you have already connected the serial port of your Linux box to a switch console port via a serial cable.
To connect a Linux terminal to the serial port of your Linux system, you can use a command-line screen manager tool called screen .
Install screen on Linux
For Ubuntu, Debian or Linux Mint:
To install screen on Ubuntu, Debian or Linux Mint:
$ sudo apt-get install screenFor CentOS, Fedora or RHEL:
To install screen on CentOS, Fedora, or RHEL:
Connect to a Serial Port with screen utility
Traditionally in Linux, the first serial port (COM1) is assigned a name /dev/ttyS0 , the second serial port (COM2) assigned /dev/ttyS1 , etc. If you specify a serial port name as the first argument of the screen command, the current terminal window where you run screen will be directly connected to the serial port.
Thus, to connect to a serial port, simply run the following command from a terminal:
Optionally, you can specify baud rate (e.g., 1200, 9600, 19200) as the second parameter as follows.
Once connected to a serial port, you will then be able to access the switch console port from the terminal.
To terminate the current screen session, type Ctrl-A + k . If you want to temporarily detach from the screen session, type Ctrl-A + d . After detached, you can re-attached to the session later by running:
Support Xmodulo
This website is made possible by minimal ads and your gracious donation via PayPal or credit card
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.