- Linux serial port list
- Working with the serial console
- Contents
- Configure console access on the target machine
- Boot loader
- GRUB Legacy
- rEFInd
- Syslinux
- Kernel
- getty
- Making Connections
- Connect using a terminal emulator program
- Command line
- And, for Windows
- Graphical front-ends
- Installing Arch Linux using the serial console
- Debugging an unresponsive machine using a serial console
- Troubleshooting
- Ctrl+c and Minicom
- Resizing a terminal
- Missing ports on multi-port expansion cards
- Linux Serial Ports Using C/C++
- Overview
- Everything Is A File
- Basic Setup In C
- Configuration Setup
- Control Modes (c_cflags)
- PARENB (Parity)
- CSTOPB (Num. Stop Bits)
- Number Of Bits Per Byte
- Flow Control (CRTSCTS)
- CREAD and CLOCAL
- Local Modes (c_lflag)
- Disabling Canonical Mode
- Disable Signal Chars
- Input Modes (c_iflag)
- Software Flow Control (IXOFF, IXON, IXANY)
- Disabling Special Handling Of Bytes On Receive
- Output Modes (c_oflag)
- VMIN and VTIME (c_cc)
- Baud Rate
- Custom Baud Rates
- Saving termios
- Reading And Writing
- Writing
- Reading
- Closing
- Full Example (Standard Baud Rates)
- Issues With Getty
- Exclusive Access
- Changing Terminal Settings Are System Wide
Linux serial port list
Как получить список доступных системе COM портов в Linux? Раньше искал в /dev файлы типа ttyS*, но что-то тут не так. На моем компе имеется один физический компорт. В /dev есть 4 порта (ttyS0, ttyS1, ttyS2, ttyS3). Но, например когда пытаюсь добавить в систему принтер, визард просит выбрать порт и показывает только ОДИН доступный компорт. Всё правильно, порт всего один. Хотя в девах их 4, в визарде только 1. На другом компе физически есть 1 компорт, а в /dev их аш 5. Как из кода в Linux-e можно получить список доступных компортов? или как проверить все ttyS0, ttyS1, ttyS2, ttyS3 и найти среди них рабочий(е)(реальный(е))?
Оглавление |
|
Сообщения по теме | [Сортировка по времени | RSS] |
1. «Как получить список доступных системе COM портов? « | + / – | |
Сообщение от ACCA | ||
Высказать мнение | Ответить | Правка | ^ | Наверх | Cообщить модератору |
2. «Как получить список доступных системе COM портов? « | + / – | |
Сообщение от juvf | ||
Спасибо. Таким образом смог выделить из всех ttyS* только рабочие. А можно подобным образом получить инфу о портах типа ttyUSB*? Или достаточно по наличию в /dev/ttyUSB0 определить, что такой порт доступен системе? | ||
Высказать мнение | Ответить | Правка | ^ | Наверх | Cообщить модератору |
3. «Как получить список доступных системе COM портов? « | + / – | |||||
Сообщение от ACCA | ||||||
Смотря откуда этот /dev/ttyUSB* взялся. Если его udev или ещё какой hal сделал — почти достаточно. Посмотри, что такое /dev. Если udev filesystem, то скорее всего можно — /dev/ttyUSB* создаются и убираются динамически, если udev скрипт не глюканул. Сделай `lshal’, почитаешь много интересного про ttyUSB. dmesg | grep ttyUSB тоже поможет. Источник Working with the serial consoleAn 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. ContentsConfigure console access on the target machineBoot loaderWhen 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 LegacyEdit the GRUB Legacy configuration file /boot/grub/menu.lst and add these lines to the general area of the configuration: rEFIndrEFInd supports serial console only in text mode. Edit refind.conf and uncomment textonly . SyslinuxTo 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. KernelKernel’s output can be sent to serial console by setting the console= kernel parameter. The last specified console= will be set as /dev/console . gettyAt 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 ConnectionsConnect using a terminal emulator programPerform these steps on the machine used to connect the remote console. Command linedtermdterm 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. Minicomminicom 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 . picocompicocom 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. ScreenGNU 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 . SerialclientSerialclient[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 WindowsOn Windows machines, connect to the serial port using programs like PuTTY[4] or Terminalbpp[5]. Graphical front-endscutecom 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
Debugging an unresponsive machine using a serial consoleEven 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. TroubleshootingCtrl+c and MinicomIf 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 terminalUnlike 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: Missing ports on multi-port expansion cards
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. Источник Linux Serial Ports Using C/C++Article by:Geoffrey Hunter
OverviewUnluckily, using serial ports in Linux is not the easiest thing in the world. When dealing with the termios.h header, there are many finicky settings buried within multiple bytes worth of bitfields. This page is an attempt to help explain these settings and show you how to configure a serial port in Linux correctly. Everything Is A FileIn typical UNIX style, serial ports are represented by files within the operating system. These files usually pop-up in /dev/ , and begin with the name tty* . Common names are:
A listing of the /dev/ directory in Linux with a connected Arduino. The Arduino serial port is present as /dev/ttyACM0. To write to a serial port, you write to the file. To read from a serial port, you read from the file. Of course, this allows you to send/receive data, but how do you set the serial port parameters such as baud rate, parity, e.t.c? This is set by a special tty configuration struct . Basic Setup In CFirst we want to include a few things: Then we want to open the serial port device (which appears as a file under /dev/ ), saving the file descriptor that is returned by open() : One of the common errors you might see here is errno = 2 , and strerror(errno) returns No such file or directory . Make sure you have the right path to the device and that the device exists! Another common error you might get here is errno = 13 , which is Permission denied . This usually happens because the current user is not part of the dialout group. Add the current user to the dialout group with: You must log out and back in before these group changes come into effect. At this point we could technically read and write to the serial port, but it will likely not work, because the default configuration settings are not designed for serial port use. So now we will set the configuration correctly. When modifying any configuration value, it is best practice to only modify the bit you are interested in, and leave all other bits of the field untouched. This is why you will see below the use of &= or |= , and never = when setting bits. Configuration SetupWe need access to the termios struct in order to configure the serial port. We will create a new termios struct, and then write the existing configuration of the serial port to it using tcgetattr() , before modifying the parameters as needed and saving the settings with tcsetattr() . We can now change tty ’s settings as needed, as shown in the following sections. Before we get onto that, here is the definition of the termios struct if you’re interested (pulled from termbits.h ): Control Modes (c_cflags)The c_cflag member of the termios struct contains control parameter fields. PARENB (Parity)If this bit is set, generation and detection of the parity bit is enabled. Most serial communications do not use a parity bit, so if you are unsure, clear this bit. CSTOPB (Num. Stop Bits)If this bit is set, two stop bits are used. If this is cleared, only one stop bit is used. Most serial communications only use one stop bit. Number Of Bits Per ByteThe CS fields set how many data bits are transmitted per byte across the serial port. The most common setting here is 8 ( CS8 ). Definitely use this if you are unsure, I have never used a serial port before which didn’t use 8 (but they do exist). You must clear all of the size bits before setting any of them with &= Flow Control (CRTSCTS)If the CRTSCTS field is set, hardware RTS/CTS flow control is enabled. The most common setting here is to disable it. Enabling this when it should be disabled can result in your serial port receiving no data, as the sender will buffer it indefinitely, waiting for you to be “ready”. CREAD and CLOCALSetting CLOCAL disables modem-specific signal lines such as carrier detect. It also prevents the controlling process from getting sent a SIGHUP signal when a modem disconnect is detected, which is usually a good thing here. Setting CLOCAL allows us to read data (we definitely want that!). Local Modes (c_lflag)Disabling Canonical ModeUNIX systems provide two basic modes of input, canonical and non-canonical mode. In canonical mode, input is processed when a new line character is received. The receiving application receives that data line-by-line. This is usually undesirable when dealing with a serial port, and so we normally want to disable canonical mode. Canonical mode is disabled with: Also, in canonical mode, some characters such as backspace are treated specially, and are used to edit the current line of text (erase). Again, we don’t want this feature if processing raw serial data, as it will cause particular bytes to go missing! If this bit is set, sent characters will be echoed back. Because we disabled canonical mode, I don’t think these bits actually do anything, but it doesn’t harm to disable them just in case! Disable Signal CharsWhen the ISIG bit is set, INTR , QUIT and SUSP characters are interpreted. We don’t want this with a serial port, so clear this bit: Input Modes (c_iflag)The c_iflag member of the termios struct contains low-level settings for input processing. The c_iflag member is an int . Software Flow Control (IXOFF, IXON, IXANY)Clearing IXOFF , IXON and IXANY disables software flow control, which we don’t want: Disabling Special Handling Of Bytes On ReceiveClearing all of the following bits disables any special handling of the bytes as they are received by the serial port, before they are passed to the application. We just want the raw data thanks! Output Modes (c_oflag)The c_oflag member of the termios struct contains low-level settings for output processing. When configuring a serial port, we want to disable any special handling of output chars/bytes, so do the following: Both OXTABS and ONOEOT are not defined in Linux. Linux however does have the XTABS field which seems to be related. When compiling for Linux, I just exclude these two fields and the serial port still works fine. VMIN and VTIME (c_cc)VMIN and VTIME are a source of confusion for many programmers when trying to configure a serial port in Linux. An important point to note is that VTIME means slightly different things depending on what VMIN is. When VMIN is 0, VTIME specifies a time-out from the start of the read() call. But when VMIN is > 0, VTIME specifies the time-out from the start of the first received character. Let’s explore the different combinations: VMIN = 0, VTIME = 0: No blocking, return immediately with what is available VMIN > 0, VTIME = 0: This will make read() always wait for bytes (exactly how many is determined by VMIN ), so read() could block indefinitely. VMIN = 0, VTIME > 0: This is a blocking read of any number of chars with a maximum timeout (given by VTIME ). read() will block until either any amount of data is available, or the timeout occurs. This happens to be my favourite mode (and the one I use the most). VMIN > 0, VTIME > 0: Block until either VMIN characters have been received, or VTIME after first character has elapsed. Note that the timeout for VTIME does not begin until the first character is received. VMIN and VTIME are both defined as the type cc_t , which I have always seen be an alias for unsigned char (1 byte). This puts an upper limit on the number of VMIN characters to be 255 and the maximum timeout of 25.5 seconds (255 deciseconds). “Returning as soon as any data is received” does not mean you will only get 1 byte at a time. Depending on the OS latency, serial port speed, hardware buffers and many other things you have no direct control over, you may receive any number of bytes. For example, if we wanted to wait for up to 1s, returning as soon as any data was received, we could use: Baud RateRather than use bit fields as with all the other settings, the serial port baud rate is set by calling the functions cfsetispeed() and cfsetospeed() , passing in a pointer to your tty struct and a enum : If you want to remain UNIX compliant, the baud rate must be chosen from one of the following: Some implementation of Linux provide a helper function cfsetspeed() which sets both the input and output speeds at the same time: Custom Baud RatesAs you are now fully aware that configuring a Linux serial port is no trivial matter, you’re probably unfazed to learn that setting custom baud rates is just as difficult. There is no portable way of doing this, so be prepared to experiment with the following code examples to find out what works on your target system. GNU/Linux Method If you are compiling with the GNU C library, you can forgo the standard enumerations above just specify an integer baud rate directly to cfsetispeed() and cfsetospeed() , e.g.: termios2 Method This method relied on using a termios2 struct, which is like a termios struct but with sightly more functionality. I’m unsure on exactly what UNIX systems termios2 is defined on, but if it is, it is usually defined in termbits.h (it was on the Xubuntu 18.04 with GCC system I was doing these tests on): Which is very similar to plain old termios , except with the addition of the c_ispeed and c_ospeed . We can use these to directly set a custom baud rate! We can pretty much set everything other than the baud rate in exactly the same manner as we could for termios , except for the reading/writing of the terminal attributes to and from the file descriptor — instead of using tcgetattr() and tcsetattr() we have to use ioctl() . Let’s first update our includes, we have to remove termios.h and add the following: Please read the comment above about BOTHER . Perhaps on your system this method will work! Saving termiosAfter changing these settings, we can save the tty termios struct with tcsetattr() : Reading And WritingNow that we have opened and configured the serial port, we can read and write to it! WritingWriting to the Linux serial port is done through the write() function. We use the serial_port file descriptor which was returned from the call to open() above. ReadingReading is done through the read() function. You have to provide a buffer for Linux to write the data into. ClosingThis is a simple as: Full Example (Standard Baud Rates)Issues With GettyGetty can cause issues with serial communication if it is trying to manage the same tty device that you are attempting to perform serial communications with. To Stop Getty: Getty can be hard to stop, as by default if you try and kill the process, a new process will start up immediately. These instructions apply to older versions of Linux, and/or embedded Linux.
$ init q to reload the /etc/inittab file. Exclusive AccessIt can be prudent to try and prevent other processes from reading/writing to the serial port at the same time you are. One way to accomplish this is with the flock() system call: Changing Terminal Settings Are System WideAlthough getting and setting terminal settings are done with a file descriptor, the settings apply to the terminal device itself and will effect all other system applications that are using or going to use the terminal. This also means that terminal setting changes are persistant after the file descriptor is closed, and even after the application that changed the settings is terminated 1 . Источник |