- Заметки о Linux, электронике, радиолюбительстве
- воскресенье, 27 июля 2014 г.
- Работа с последовательным портом из консоли Linux
- Serial Port Tips for Linux
- Contents
- Addressing a Serial Port
- Serial Port File Permissions
- Configuring a Serial Port under Linux
- Opening a Serial Port
- Alternatives to socat
- Printing Timestamps Next to the Received Data
- No exclusive lock when accessing serial ports
- How To Check and Use Serial Ports Under Linux
- Display Detected System’s Serial Support Under Linux
- A note about USB based serial ports
- Listing and using USB serial ports on Linux
- Use the setserial command to check and use serial ports
- Debian/Ubuntu Linux install setserial using the apt-get command/apt command
- CentOS/RHEL/Oracle Linux install setserial using the yum command
- Using setserial to list serial ports and devices
- Listing or displaying USB serial ports on Linux
- Linux serial console programs
- Cocnlusion
Заметки о Linux, электронике, радиолюбительстве
Личный блог Вадима Кузнецова, RA3XDH
воскресенье, 27 июля 2014 г.
Работа с последовательным портом из консоли Linux
В предыдущем посте было показано как запустить UART на отладочной плате Launchpad для MSP430. Теперь рассмотрим как общаться с платой при помощи средств командной строки Linux. Используется плата с прошивкой из предыдущего поста. Для подробностей — см. под кат
Как известно, все устройства последовательных портов представлены файлами устройств в каталоге /dev.Через эти файлы и происходит общение ОС Linux с внешним устройством на последовательном порту. Чтобы передать что-то на внешнее устройство нужно записать данные в файл устройства, а чтобы считать информацию из устройства — прочитать данные из файла устройства. Это можно делать при помощи команд cat и echo так же как для обычных файлов на диске. Или внутри программы на С при помощи вызовов ioctl(), read() и write() или библиотеки termios.
Физическим последовательным портам RS232, к которым подключались диалапные модемы на старых компьютерах, соответствуют файлы устройств /dev/ttyS*, начиная с /dev/ttyS0. Виртуальным последовательным портам, которые создаются различными конвертерами USB UART соответствуют файлы устройств /dev/ttyUSB* и /dev/ttyACM*. Ядро Linux автоматически разпознаёт подключенное устройство, загружает для него драйвер и создаёт файл устройства. Вручную устанавливать драйвер, как в ОС Windows не требуется. Например, если подключить к USB преобразователь USB UART FT232, то создаётся файл устройства /dev/ttyUSB0, с которым можно работать также как и с обычным последовательным портом. На плате Launcpad находится микросхема TUSB3410, которая тоже представляет собой конвертер USB UART. Если подключить её к USB, то создаётся файл устройства /dev/ttyACM0. Чтобы общаться с платой нужно что-либо писать/читать с этого файла.
Чтобы пользователь мог читать или писать в файл устройства последовательного порта, его нужно добавить в группу dialout. Иначе работать с последовательным портом сможет только администратор root.
Простейшим приложением с графическим интерфейсом, которое работает с последовательным портом, является CuteCOM. Он обычно уже есть в вашем дистрибутиве Linux. Его можно установить из репозиториев. При помощи CuteCOM мы работали с платой в предыдущем посте. Выглядит CuteCOM вот так:
Работать с ним крайне просто. Указываем нужное устройство, если его нет в списке, то его можно впечатать вручную. Затем указываем скорость и параметры и нажимаем OpenDevice. В окне видим данные, которые пришли от устройства. В поле ввода в нижней части можем печать строку символов, которые предаются на устройство. Чтобы передать данный нажимаем Enter и смотрим ответ устройства в окне.
Теперь рассмотрим как работать с COM-портом из командной строки. Для этого служат три команды: stty, cat и echo.
Команда stty устанавливает параметры и скорость COM-порта. Её формат:
stty -F
Чтобы установить параметры для платы Launchpad для соединения на скорости 9600 нужно выполнить:
$ stty 9600 -F /dev/ttyACM0 raw -echo
Параметр raw устанавливает, что данные в компьютер передаются байт за байтом так же как приходят в порт без преобразований. Аппаратное управление потоком отключено. Подробнее о том, что включает и выключает raw — см. man stty. Если не включить raw, то скорее всего ничего работать не будет.
Теперь в той же консоли нужно набрать
$ cat /dev/ttyACM0
И можно смотреть данные, которые приходят от платы. Выход — нажать Ctrl+C.
Теперь нажимаем на плате RESET и видим, что в консоди напечатался текст.
Чтобы передать в плату данные, в другой консоли нужно использовать команду echo и перенаправление вывода в файл устройства. Наберём в другой консоли:
$ echo "1">/dev/ttyACM0
Видим, что на плате загорелся красный светодиод и в первой консоли было выдано сообщение об этом. Чтобы убрать конец строки в передаваемых данных, то нужно использовать запуск echo -n, а чтобы интерпретировать 16-ричные коды — нужно echo -e. Ключи можно комбинировать.
В итоге должно получиться так:
Чтобы увидеть 16-ричные коды данных, приходящих от устройства, нужно использовать команду hexdump:
$ cat /dev/ttyACM0|hexdump -C
Получится вот так:
Чтобы иметь вывод данных от устройство на экран и в текстовый файл нужно использовать tee:
Источник
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.
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.
Источник
How To Check and Use Serial Ports Under Linux
Display Detected System’s Serial Support Under Linux
Simple run the dmesg command:
$ dmesg | grep tty
A note about USB based serial ports
USB to RS232 adapter cable connects from the USB port of a computer to a device. Such serial to USB adapter connects to devices for configuration or programming under Linux. Here is what the dmesg command displays when you enter USB adapter:
$ dmesg
## use grep command/egrep command to filter out USB devices ##
$ dmesg | grep -i serial
$ dmesg | grep -i FTDI
Listing and using USB serial ports on Linux
Here is how it looks when I attached USB device:
$ sudo dmesg | more
Use the setserial command to check and use serial ports
The setserial is a program designed to set and/or report the configuration information associated with a serial port. This information includes what I/O port and IRQ a particular serial port is using, and whether or not the break key should be interpreted as the Secure Attention Key, and so on.
Debian/Ubuntu Linux install setserial using the apt-get command/apt command
$ sudo apt install setserial
CentOS/RHEL/Oracle Linux install setserial using the yum command
$ sudo yum install setserial
Fedora Linux user try the dnf command:
$ sudo dnf install setserial
Using setserial to list serial ports and devices
Now we installed required package. Open the termial and then type the following setserial command:
$ setserial -g /dev/ttyS[0123]
If you get an error/warning that reads as “Permission denied,” try running the command as the root user. For example, I am running it using the sudo command/su command:
$ sudo setserial -g /dev/ttyS[0123]
The setserial with -g option help to find out what physical serial ports your Linux box has.
Listing or displaying USB serial ports on Linux
Try:
$ sudo setserial -g /dev/ttyUSB[01]
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Linux serial console programs
Once serial ports identified you can configure Linux box and use serial ports using various utilities:
- minicom– The best friendly serial communication program for controlling modems and connecting to dump devices
- wvidial or other GUI dial up networking program – a PPP dialer with built-in intelligence.
- Screen Command: Set Baud Rate [ Terminal Communication ]
- getty / agetty – agetty opens a tty port, prompts for a login name and invokes the /bin/login command.
- grub / lilo configuration – To configure serial port as the system console
Cocnlusion
You learned how to list or check serial ports including USB based adptor on Linux.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I don’t know if this is the place, but I’m looking for information that is similar. I have 2 machines setup through a null modem. I want to read through the com port from one machine to the other. The sending machine is running Windows sending through COM1: and the receiving computer is Linux Red Hat. Any help on this would be appreciated.
You can use pyserial ,its a python package,can be used to read and write in serial ports
another simple serial console program not mentioned is gtkterm.
I want to advise you that probably there is an error in the last sentence “seserial with -g option help to find out what physical serial ports your Linux box has.”; isn’t it setserial?
I have 4 standard serial ports defined, /dev/ttyS0-4, but I added a PCI-E 16 port serial adapter, and I have not found a way to connect anything to the upper 16 ports.
How do you create the virtual links? what options do you give setserial to define the new ports?
it dosn’t work 🙁 I can’t connect to my ASA using debian.
Daemon is a program called getty used by UNIX/Linux systems. There are many different versions of getty. The first modem detected is /dev/ttys0 or /dev/ttys1. To create a link to the devices file so that you can view modem information. Type ln -s /dev/ttys1 /dev/modem.
It is essential to set the modem to AUTO ANSWER using getty.
download minicom from alioth.debian.org/projects/minicom.
create a modem config file by entering minicom -s from the root command line
select the options you want to configure using AT commands
connect to the modem by typing in minicom
Thanks very useful..save my time 🙂
Hi,everybody
I have a serial PCI card with two ports but neither of them is working, on Linux fedora 16. I have tried using “gtkterm” and “minicom” but unfortunately I can’t make a serial connection to my Cisco lab. Here is my output when I issue the command: “setserial -g /dev/ttyS[0123]”.
/dev/ttyS0, UART: 16550A, Port: 0xec00, IRQ: 16
/dev/ttyS1, UART: 16550A, Port: 0xe880, IRQ: 16
/dev/ttyS2, UART: unknown, Port: 0x03e8, IRQ: 4
/dev/ttyS3, UART: unknown, Port: 0x02e8, IRQ: 3
also I want to mention that when I try to connet throught the terminal it generates a message like so: ” Cannot open /dev/ttyS0: Permission denied”.
any help please.
abdel
Check the permissions on /dev/ttyS0… Likely problem is it’s owned by root, and is part of the uucp group. Add yourself to the uucp group, and all should be better. I’m curious to know if this is enough for you as I am having problems communicating with a serial port on Linux as well. I got past the permissions stuff, but it is still not working.
Thanks Tom,
I actually I tried but it’s does not work, still says “permission denied”. I would appreciate if you explain to me step by step the procedure how to do it, I’m knew to Linux.
Best Regards
Abdel
1) ls -la /dev/ttyS0 — This will report the permissions on the port. Typically, this will say crw-rw—- 1 root uucp. The “c” in the string indicates that it’s a “character device” the first “rw” indicates that the owner has read/write permission. The second “rw” means that the group has read/write permissions. The “—” indicates that the rest of the world has no permissions. After the “—-“, “root” indicates that the owner of the device is root, and that the group id is “uucp”. So, you either need to be root, or a member of the uucp group to have read/write access to the port.
2) To add yourself to the uucp group (to get read/write access), you need to edit the file /etc/group, and add your user name to the line that begins with “uucp:” User names are separated by commas, so add a comma, then your user name to the end of the line. You will need root permissions to edit this file.
3) log out, and log back in because group associations are made at login time, and are not queried on each request.
Thanks Tom,
here is my output from the group file I have added my username to it but does not work.
I will just give up.Thanks a lot for your help I relay appreciate it.
Your entry in /etc/group is incorrect. If you read my previous post, I said to add your user id to the line that _begins_ with uucp. You added uucp to the group of users that can access your account. You want an entry in the /etc/group file that looks something like:
The critical element is that it’s the line that begins with uucp
It works. I just add my username to ” dialout ” and it worked fine. Iwould like to thank you for you time and support.
Best Regards
Abdel
hi,
I have connected the SIM300(gsm model) to my pc running ubuntu. I need a code to send a AT command to the GSM module and it should read and display the reply.
Please let me know steps.
I tried so many methods and codes, but no use…
i need C code(program).
all my ttyS* shows unknown, earlier it was working fine, now it doesnt recognise
setserial -g /dev/ttyS*
/dev/ttyS0, UART: unknown, Port: 0x03f8, IRQ: 4
/dev/ttyS1, UART: unknown, Port: 0x02f8, IRQ: 3
/dev/ttyS2, UART: unknown, Port: 0x03e8, IRQ: 4
/dev/ttyS3, UART: unknown, Port: 0x02e8, IRQ: 3
#cat /etc/redhat-release
CentOS Linux release 6.0 (Final)
#dmesg | grep tty
console [tty0] enabled
can u pls help me
tried spending time in google two days, still no success, tried connecting a brand new device too, still no success.
Sorry, but that second sentence is not necessarily true. I have a PC with two dual com port adapters. Windows sees them as COM1 -> COM4 (there is no built in COM port). Linux sees them as /dev/ttyS4->/dev/ttyS7.
/dev/ttyS0-/devttyS3 are apparently reserved, exist whether or not a physical port exists, and /dev/ttyS0 for certain is “special” in that it is used by the default terminal window:
I think minicom still superior to other console utility.
Hi All tried all of the above and still get permission denied . HELP
Kevin
/bpq$ setserial -g /dev/ttyS[012345657
/bpq$ setserial -g /dev/ttyS[012345657]
sudo setserial -g /dev/ttyS1
Hiiiiiiiii
Please help me
i am install minicom and use serial modem sim300 v7.03 but there is problem to type AT cmd on minicom console…….
Edgeports are very easy to use the firmware is on Ubuntu they are from 2 ports to 16+ I bought my last two of them on ebay.
Jim
Hi all..
I got problem to connect with my USB serial port,
i already create
ln -s /dev/ttyUS0
and check dmesg | grep tty
[ 0.000000] console [tty0] enabled
[ 7.722004] systemd[1]: Created slice system-getty.slice.
[ 3659.524452] usb 1-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
[ 4850.183339] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[ 4857.907567] usb 1-1.1: FTDI USB Serial Device converter now attached to ttyUSB0
when running SDNC program and select com1 will shown “port is already in use”
hi, have are you\
i have a problem with machine xnc . old version sistem operating linux,
pc removed battery cmos . but change battery do it so machine different data serial port linux dont recognized machine.
how can you slove this problem
your help wil be welcome
Источник