Using serial port in linux

Working with the serial console

An Arch Linux machine can be configured for connections via the serial console port, which enables administration of a machine even if it has no keyboard, mouse, monitor, or network attached to it.

Installation of Arch Linux is possible via the serial console as well.

A basic environment for this scenario is two machines connected using a serial cable (9-pin connector cable). The administering machine can be any Unix/Linux or Windows machine with a terminal emulator program (PuTTY or Minicom, for example).

The configuration instructions below will enable boot loader menu selection, boot messages, and terminal forwarding to the serial console.

Contents

Configure console access on the target machine

Boot loader

When using GRUB with a generated grub.cfg , edit /etc/default/grub and enable serial input and output support:

Next add the GRUB_SERIAL_COMMAND variable and set the options for the serial connection. For COM1 ( /dev/ttyS0 ) with baud rate of 115200 bit/s:

Read GRUB’s manual on Using GRUB via a serial line and the serial command for detailed explanation of the available options.

GRUB Legacy

Edit the GRUB Legacy configuration file /boot/grub/menu.lst and add these lines to the general area of the configuration:

rEFInd

rEFInd supports serial console only in text mode. Edit refind.conf and uncomment textonly .

Syslinux

To enable serial console in Syslinux, edit syslinux.cfg and add SERIAL as the first directive in the configuration file.

For COM1 ( /dev/ttyS0 ) with baud rate of 115200 bit/s:

The serial parameters are hardcoded to 8 bits, no parity and 1 stop bit.[1]. Read Syslinux Wiki:Config#SERIAL for the directive’s options.

Kernel

Kernel’s output can be sent to serial console by setting the console= kernel parameter. The last specified console= will be set as /dev/console .

getty

At boot, systemd-getty-generator(8) will start a getty instance for each console specified in the kernel command line.

If you have not configured console= in kernel command line start serial-getty@device.service . For /dev/ttyS0 (COM1) that would be serial-getty@ttyS0.service . Enable the service to start it at boot.

Unless specified otherwise in the kernel command line, getty will be expecting 38400 bit/s baud rate, 8 data bits, no parity and one stop bit-times.

Making Connections

Connect using a terminal emulator program

Perform these steps on the machine used to connect the remote console.

Command line

dterm

dterm AUR is a tiny serial communication program. If you invoke it without parameters, it will connect to /dev/ttyS0 at 9600 baud by default. The following example connect to /dev/ttyS0 at 115200 baud, with 8 data bits, no parity bit and 1 stop bit-times:

See its homepage[2] for more examples.

Minicom

minicom can be obtained from the official repositories. Start Minicom in setup mode:

Using the textual navigation menu, change the serial port settings to the following:

Press Enter to exit the menus (pressing Esc will not save changes). Remove the modem Init and Reset strings, as we are not connecting to a modem. To do this, under the Modem and Dialing menu, delete the Init and Reset strings. Optionally save the configuration by choosing save setup as dfl from the main menu. Restart minicom with the serial cable connected to the target machine. To end the session, press Ctrl+A followed by Ctrl+X .

Читайте также:  Как переименовать локальный диск windows 10
picocom

picocom is a tiny dumb-terminal emulation program that is very like minicom, but instead of mini, it is pico. The following example connect to ttyS0 at 9600 bps:

See its manual for detailed usage.

Screen

GNU Screen is able to connect to a serial port. It will connect at 9600 baud by default:

A different baud rate (e.g. 115200) may be specified on the command line.

To end the session, press Ctrl+a followed by K . Alternatively, press Ctrl+a , type :quit and confirm it by pressing Enter .

Serialclient

Serialclient[3] is a CLI client for serial connection written in ruby. Install ruby package, then install it with the following:

Then, you can use like this:

And, for Windows

On Windows machines, connect to the serial port using programs like PuTTY[4] or Terminalbpp[5].

Graphical front-ends

cutecom AUR is another gui enabled serial monitor.

putty is also available for Linux.

moserial is a gtk-based serial terminal, primarily intended for technical users and hardware hackers who need to communicate with embedded systems, test equipment, and serial consoles.

Installing Arch Linux using the serial console

  1. Connect to the target machine using the method described above.
  2. Boot the target machine using the Arch Linux installation CD.
  3. When the bootloader appears, select Boot Arch Linux () and press Tab to edit
  4. Append console=ttyS0,115200 and press Enter .
  5. Now systemd should detect ttyS0 and spawn a serial getty on it. Login as root and start the installation as usual.

Debugging an unresponsive machine using a serial console

Even though [7] has only raw and terse instructions, it presents the full scene. It is important to note that here, the machine under test got unresponsive in a reproducible manner. And that it happened during normal operation. So it could be accessed normally before it needed debugging. However, in general, the serial console is also useful for debugging boot issues. Perhaps by configuring the boot loader by hand at machine startup time. Also note the mentioned netconsole within the P.S paragraph of the external link from this section.

Troubleshooting

Ctrl+c and Minicom

If you are having trouble sending a Ctrl+c command through minicom you need to switch off hardware flow control in the device settings ( minicom -s ), which then enables the break.

Resizing a terminal

Unlike ssh, serial connections do not have a mechanism to transfer something like SIGWINCH when a terminal is resized. This can cause weird problems with some full-screen programs (e.g. less ) when you resize your terminal emulator’s window.

Resizing the terminal via stty is a workaround:

However, this requires you to manually input the proper geometry. The following methods should be simpler.

1. There is a lesser-known utility called resize , shipped with xterm , that can solve this problem. Invoke it without parameters after you resize the terminal emulator’s window:

2. If you do not want to install xterm, it is possible to do the same work via a shell function. Put the following function into your zshrc and invoke it without parameters after resizing the terminal emulator’s window:

Читайте также:  Как поставит виртуальную mac os

Missing ports on multi-port expansion cards

This article or section needs expansion.

The number of serial ports using the generic 8250 driver on the default kernel configuration is set to 4 at runtime with a maximum of 32. This will prevent the creation of /dev/ttyS4 and above. Counting the typical built in serial port on the motherboard this prevents the use of the 4th serial port on a 4 port expansion card.

Источник

Serial Port Tips for Linux

Contents

Addressing a Serial Port

Built-in serial ports tend to get the same device filename everytime, like /dev/ttyS0 for the first one, /dev/ttyS1 for the second one, and so on.

However, USB virtual serial ports get a different filename each time, depending on the kind of device and the order with which the USB ports are connected to the system. Typically, such device filenames look like /dev/ttyACM0 or /dev/ttyUSB0, but such names are often unpredictable.

You have several options:

  • Manually inspect the tty* files under /dev, in order to find out which one gets created when a particular USB device is connected.
  • Use a filename under /dev/serial/by-id or /dev/serial/by-path.
  • Use a script like FindUsbSerialPort.sh in order to find a USB serial port filename by manufacturer name, serial number, etc.
  • Write a UDEV rules file that assigns a fixed filename to your particular USB device.

If you are using many USB serial port adapters at the same time, finding out which one is which can be time-consuming. The following commands print the associated filename whenever you connect or detach a serial port.

Note that, on Ubuntu/Debian, you will need to install package inotify-tools beforehand, which provides the inotifywait tool the following commands use.

These commands only work if there is at least one other USB serial port adapter, that is, if directory /dev/serial/by-path already exists:

The parenthesis «()» create a subshell, so that variable DIR does not remain set afterwards.

The «sh -c» and the \$ extra quoting above are just a trick, so that you can specify the directory to watch at the beginning of the line using a single, temporary variable for just that command.

The commands above stop working if you remove the last virtual serial port device and subdirectory /dev/serial/by-path is automatically removed.

Depending on the Linux kernel version, you may not get ‘create’ notifications, only ‘delete’ ones. You will then have to plug and unplug the USB serial port adapter in order to see the associated filename. You may also need to restart the command above to see the notifications if you plug and unplug again.

Serial Port File Permissions

You may find that your user account has no right to access the serial port devices. Find out the file permissions like this:

On Ubuntu/Debian, the easiest way to grant yourself the necessary rights is to make your user account a member of the «dialout» group like this:

You will have to log out and log in again for the group membership change to take effect.

Configuring a Serial Port under Linux

Set the default configuration with stty to 9600 bps, 8N1, no flow control:

You only need to configure the serial port with stty if you are going to be using generic file tools like cat, which often fail on serial ports anyway. Other tools like socat or dedicated serial port terminal software can configure all serial port parameters themselves.

Opening a Serial Port

Say you have the following scenario:

  • Your device reacts to single keypresses.
    Therefore, you do not want line editing on the local side, because characters need to be sent straight away.
    An example device would be the Bus Pirate.
  • You want to use a standard text console.
  • You want to terminate the connection when you press Ctrl+C.
Читайте также:  Как отключить индексировать дисков windows 10

You can connect to your device with the following command:

If the backspace key does not work, try using Ctrl+H instead.

Depending on your device, you may need to add «crnl» to either the STDIO or the tty side, in order to convert the line termination characters properly.

Watch out that socat’s address specification requires some unusual quoting. For example, in order to open the following serial port:

you need to type in Bash the following socat address:

The open-serial-port-in-new-console.sh script has a Bash routine that performs such quoting.

Say that you only want to print any data received, with timestamps and hex codes, but not send any data:

Option ‘setlk’ does not seem to work when opening the serial port in read-only mode. This is an example output for the command above:

Alternatives to socat

Check out script open-serial-port-in-new-console.sh, which will let you comfortably choose any of the tools below when opening your serial ports.

  • picocom -b 115200 -p n -d 8 /dev/serial-port-device
    Exit with Ctrl+A, Ctrl+X.
  • minicom -b 115200 -8 -D /dev/serial-port-device
  • screen /dev/serial-port-device 115200
    Exit with Ctrl+A, ‘\’.
  • C-Kermit
  • cutecom
  • gtkterm -s 115200 -p /dev/serial-port-device
  • putty -serial COM8 # Only on Windows.
  • plink # Only on Windows.

Printing Timestamps Next to the Received Data

Here are some alternatives:

  • I have written a script to dump all bytes with timestamps and their ASCII character names: https://github.com/rdiez/Tools/tree/master/AnnotateWithTimestamps
  • socat’s option -v generates an extra output log to stderr which includes timestamps.
  • Tool ts (see Ubuntu package moreutils) copies stdin to stdout prepending timestams. Usage example:
    unbuffer $COMMAND | ts «%F %H:%M:%.S»
    Unfortunately, if you are using socat, you will have to remove «icanon=0,echo=0» from the STDIO side, which may have unpleasant side-effects.
    As an alternative to unbuffer, you can use stdbuf -o0 .
  • Tool grabserial reads lines from a serial port and writes them to a standard output, optionally prepending timestamps, which allows you to easily time processes, like booting an embedded operating system.

No exclusive lock when accessing serial ports

I was surprised to learn that several Linux processes can open a given serial port at the same time. This usually makes a mess of the data. If you make a mistake and try to use the same port from several concurrent scripts, it may take a while to figure out why the data is getting chopped and mixed up in random ways.

There is no exclusive lock when opening serial port files, like there is under Windows. As far as I know, there is no way to enforce such a protection against concurrent access at system level. If you do know how to achieve that, please drop me a line!

There is a work-around if all processes cooperate. Tool socat implements arguments setlk, which uses «fcntl(fd, F_SETLK, . )», and argument flock-ex-nb, which uses «flock(fd, LOCK_EX|LOCK_NB)». Interestingly enough, those two file-locking mechanisms seem to be independent from each other, at least under Linux. If a process uses one method, then other processes that use the same method will realise that the file is already locked. However, processes that do not use any locking method will not be affected at all.

Источник

Оцените статью