Serial ports
Single-page view · as markdown
Support for Serial devices
Peios Kernel / Hardware and drivers / Driver development / Serial ports
Serial drivers #
Low Level Serial API
Peios Kernel / Hardware and drivers / Driver development / Serial ports
This document is meant as a brief overview of some aspects of the new serial driver. It is not complete, any questions you have should be directed to <rmk@arm.linux.org.uk>
The reference implementation is contained within amba-pl011.c.
Low Level Serial Hardware Driver #
The low level serial hardware driver is responsible for supplying port information (defined by uart_port) and a set of control methods (defined by uart_ops) to the core serial driver. The low level driver is also responsible for handling interrupts for the port, and providing any console support.
Console Support #
The serial core provides a few helper functions. This includes decoding command line arguments (uart_parse_options()).
There is also a helper function (uart_console_write()) which performs a character by character write, translating newlines to CRLF sequences. Driver writers are recommended to use this function rather than implementing their own version.
Locking #
It is the responsibility of the low level hardware driver to perform the necessary locking using port->lock. There are some exceptions (which are described in the struct uart_ops listing below.)
There are two locks. A per-port spinlock, and an overall semaphore.
From the core driver perspective, the port->lock locks the following data:
port->mctrl
port->icount
port->state->xmit.head (circ_buf->head)
port->state->xmit.tail (circ_buf->tail)
The low level driver is free to use this lock to provide any additional locking.
The port_sem semaphore is used to protect against ports being added/ removed or reconfigured at inappropriate times. Since v2.6.27, this semaphore has been the 'mutex' member of the tty_port struct, and commonly referred to as the port mutex.
uart_ops #
struct uart_ops #
- interface between serial_core and the driver
Definition
;
Members
tx_empty:unsigned int ()(struct uart_port *port)set_mctrl:void ()(struct uart_port *port, unsigned int mctrl)get_mctrl:unsigned int ()(struct uart_port *port)stop_tx:void ()(struct uart_port *port)start_tx:void ()(struct uart_port *port)throttle:void ()(struct uart_port *port)unthrottle:void ()(struct uart_port *port)send_xchar:void ()(struct uart_port *port, char ch)stop_rx:void ()(struct uart_port *port)start_rx:void ()(struct uart_port *port)enable_ms:void ()(struct uart_port *port)break_ctl:void ()(struct uart_port *port, int ctl)startup:int ()(struct uart_port *port)shutdown:void ()(struct uart_port *port)flush_buffer:void ()(struct uart_port *port)set_termios:void ()(struct uart_port *port, struct ktermios *new, struct ktermios *old)set_ldisc:void ()(struct uart_port *port, struct ktermios *termios)pm:void ()(struct uart_port *port, unsigned int state, unsigned int oldstate)type:const char *()(struct uart_port *port)release_port:void ()(struct uart_port *port)request_port:int ()(struct uart_port *port)config_port:void ()(struct uart_port *port, int type)verify_port:int ()(struct uart_port *port, struct serial_struct *serinfo)ioctl:int ()(struct uart_port *port, unsigned int cmd, unsigned long arg)poll_init:int ()(struct uart_port *port)poll_put_char:void ()(struct uart_port *port, unsigned char ch)poll_get_char:int ()(struct uart_port *port)
Description
This structure describes all the operations that can be done on the physical hardware.
This function tests whether the transmitter fifo and shifter for the
port is empty. If it is empty, this function should return
TIOCSER_TEMT, otherwise return 0. If the port does not support this
operation, then it should return TIOCSER_TEMT.
Locking: none. Interrupts: caller dependent. This call must not sleep
This function sets the modem control lines for port to the state described by mctrl. The relevant bits of mctrl are:
-
TIOCM_RTSRTS signal. -
TIOCM_DTRDTR signal. -
TIOCM_OUT1OUT1 signal. -
TIOCM_OUT2OUT2 signal. -
TIOCM_LOOPSet the port into loopback mode.If the appropriate bit is set, the signal should be driven active. If the bit is clear, the signal should be driven inactive.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Returns the current state of modem control inputs of port. The state of the outputs should not be returned, since the core keeps track of their state. The state information should include:
-
TIOCM_CARstate of DCD signal -
TIOCM_CTSstate of CTS signal -
TIOCM_DSRstate of DSR signal -
TIOCM_RIstate of RI signalThe bit is set if the signal is currently driven active. If the port does not support CTS, DCD or DSR, the driver should indicate that the signal is permanently active. If RI is not available, the signal should not be indicated as active.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Stop transmitting characters. This might be due to the CTS line becoming inactive or the tty layer indicating we want to stop transmission due to an
XOFFcharacter.The driver should stop transmitting characters as soon as possible.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Start transmitting characters.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Notify the serial driver that input buffers for the line discipline are close to full, and it should somehow signal that no more characters should be sent to the serial port. This will be called only if hardware assisted flow control is enabled.
Locking: serialized with unthrottle() and termios modification by the tty layer.
Notify the serial driver that characters can now be sent to the serial port without fear of overrunning the input buffers of the line disciplines.
This will be called only if hardware assisted flow control is enabled.
Locking: serialized with throttle() and termios modification by the tty layer.
Transmit a high priority character, even if the port is stopped. This is used to implement XON/XOFF flow control and
tcflow(). If the serial driver does not implement this function, the tty core will append the character to the circular buffer and then callstart_tx()/stop_tx()to flush the data out.Do not transmit if ch == '\0' (
__DISABLED_CHAR).Locking: none. Interrupts: caller dependent.
Start receiving characters.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Stop receiving characters; the port is in the process of being closed.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Enable the modem status interrupts.
This method may be called multiple times. Modem status interrupts should be disabled when the shutdown() method is called.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Control the transmission of a break signal. If ctl is nonzero, the break signal should be transmitted. The signal should be terminated when another call is made with a zero ctl.
Locking: caller holds tty_port->mutex
Grab any interrupt resources and initialise any low level driver state. Enable the port for reception. It should not activate RTS nor DTR; this will be done via a separate call to set_mctrl().
This method will only be called when the port is initially opened.
Locking: port_sem taken. Interrupts: globally disabled.
Disable the port, disable any break condition that may be in effect, and free any interrupt resources. It should not disable RTS nor DTR; this will have already been done via a separate call to set_mctrl().
Drivers must not access port->state once this call has completed.
This method will only be called when there are no more users of this port.
Locking: port_sem taken. Interrupts: caller dependent.
Flush any write buffers, reset any DMA state and stop any ongoing DMA transfers.
This will be called whenever the port->state->xmit circular buffer is cleared.
Locking: port->lock taken. Interrupts: locally disabled. This call must not sleep
Change the port parameters, including word length, parity, stop bits. Update port->read_status_mask and port->ignore_status_mask to indicate the types of events we are interested in receiving. Relevant ktermios::c_cflag bits are:
-
CSIZE- word size -
CSTOPB- 2 stop bits -
PARENB- parity enable -
PARODD- odd parity (whenPARENBis in force) -
ADDRB- address bit (changed through uart_port::rs485_config()). -
CREAD- enable reception of characters (if not set, still receive characters from the port, but throw them away). -
CRTSCTS- if set, enable CTS status change reporting. -
CLOCAL- if not set, enable modem status change reporting.Relevant ktermios::c_iflag bits are:
-
INPCK- enable frame and parity error events to be passed to the TTY layer. -
BRKINT/PARMRK- both of these enable break events to be passed to the TTY layer. -
IGNPAR- ignore parity and framing errors. -
IGNBRK- ignore break errors. IfIGNPARis also set, ignore overrun errors as well.The interaction of the ktermios::c_iflag bits is as follows (parity error given as an example):
============ ======= ======= =========================================
Parity error INPCK IGNPAR
============ ======= ======= =========================================
n/a 0 n/a character received, marked as %TTY_NORMAL
None 1 n/a character received, marked as %TTY_NORMAL
Yes 1 0 character received, marked as %TTY_PARITY
Yes 1 1 character discarded
============ ======= ======= =========================================
Other flags may be used (eg, xon/xoff characters) if your hardware supports hardware "soft" flow control.
Locking: caller holds tty_port->mutex Interrupts: caller dependent. This call must not sleep
Notifier for discipline change. See Documentation/driver-api/tty/tty_ldisc.rst.
Locking: caller holds tty_port->mutex
Perform any power management related activities on the specified port. state indicates the new state (defined by enum uart_pm_state), oldstate indicates the previous state.
This function should not be used to grab any resources.
This will be called when the port is initially opened and finally
closed, except when the port is also the system console. This will
occur even if CONFIG_PM is not set.
Locking: none. Interrupts: caller dependent.
Return a pointer to a string constant describing the specified port,
or return NULL, in which case the string 'unknown' is substituted.
Locking: none. Interrupts: caller dependent.
Release any memory and IO region resources currently in use by the port.
Locking: none. Interrupts: caller dependent.
Request any memory and IO region resources required by the port. If any
fail, no resources should be registered when this function returns, and
it should return -EBUSY on failure.
Locking: none. Interrupts: caller dependent.
Perform any autoconfiguration steps required for the port. type
contains a bit mask of the required configuration. UART_CONFIG_TYPE
indicates that the port requires detection and identification.
port->type should be set to the type found, or PORT_UNKNOWN if no
port was detected.
UART_CONFIG_IRQ indicates autoconfiguration of the interrupt signal,
which should be probed using standard kernel autoprobing techniques.
This is not necessary on platforms where ports have interrupts
internally hard wired (eg, system on a chip implementations).
Locking: none. Interrupts: caller dependent.
Verify the new serial port information contained within serinfo is suitable for this port type.
Locking: none. Interrupts: caller dependent.
Perform any port specific IOCTLs. IOCTL commands must be defined using the standard numbering system found in <asm/ioctl.h>.
Locking: none. Interrupts: caller dependent.
Called by kgdb to perform the minimal hardware initialization needed to support poll_put_char() and poll_get_char(). Unlike startup(), this should not request interrupts.
Locking: tty_mutex and tty_port->mutex taken.
Interrupts: n/a.
Called by kgdb to write a single character ch directly to the serial port. It can and should block until there is space in the TX FIFO.
Locking: none. Interrupts: caller dependent. This call must not sleep
Called by kgdb to read a single character directly from the serial
port. If data is available, it should be returned; otherwise the
function should return NO_POLL_CHAR immediately.
Locking: none. Interrupts: caller dependent. This call must not sleep
Other functions #
uart_write_wakeup() #
void schedule write processing
Parameters
struct uart_port *port: port to be processed
Description
This routine is used by the interrupt handler to schedule processing in the software interrupt portion of the driver. A driver is expected to call this function when the number of characters in the transmit buffer have dropped below a threshold.
Locking: port->lock should be held
uart_update_timeout() #
void update per-port frame timing information
Parameters
struct uart_port *port: uart_port structure describing the portunsigned int cflag: termios cflag valueunsigned int baud: speed of the port
Description
Set the port frame timing information from which the FIFO timeout value is derived. The cflag value should reflect the actual hardware settings as number of bits, parity, stop bits and baud rate is taken into account here.
Locking: caller is expected to take port->lock
uart_get_baud_rate() #
unsigned int return baud rate for a particular port
Parameters
struct uart_port *port: uart_port structure describing the port in question.struct ktermios *termios: desired termios settingsconst struct ktermios *old: old termios (orNULL)unsigned int min: minimum acceptable baud rateunsigned int max: maximum acceptable baud rate
Description
Decode the termios structure into a numeric baud rate, taking account of the
magic 38400 baud rate (with spd_* flags), and mapping the B0 rate to 9600
baud.
If the new baud rate is invalid, try the old termios setting. If it's still invalid, we try 9600 baud. If that is also invalid 0 is returned.
The termios structure is updated to reflect the baud rate we're actually going to be using. Don't do this for the case where B0 is requested ("hang up").
Locking: caller dependent
uart_get_divisor() #
unsigned int return uart clock divisor
Parameters
struct uart_port *port: uart_port structure describing the portunsigned int baud: desired baud rate
Description
Calculate the divisor (baud_base / baud) for the specified baud, appropriately rounded.
If 38400 baud and custom divisor is selected, return the custom divisor instead.
Locking: caller dependent
uart_get_lsr_info() #
int get line status register info
Parameters
struct tty_struct *tty: tty associated with the UARTstruct uart_state *state: UART being queriedunsigned int __user *value: returned modem value
uart_console_write() #
void write a console message to a serial port
Parameters
struct uart_port *port: the port to write the messageconst char *s: array of charactersunsigned int count: number of characters in string to writevoid (*putchar)(struct uart_port *, unsigned char): function to write character to port
uart_parse_earlycon() #
int Parse earlycon options
Parameters
char *p: ptr to 2nd field (ie., just beyond '<name>,')enum uart_iotype *iotype: ptr for decoded iotype (out)resource_size_t *addr: ptr for decoded mapbase/iobase (out)char **options: ptr for <options> field;NULLif not present (out)
Description
-
Decodes earlycon kernel command line parameters of the form:
- earlycon=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
- console=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
-
The optional form:
- earlycon=<name>,0x<addr>,<options>
- console=<name>,0x<addr>,<options>
is also accepted; the returned iotype will be UPIO_MEM.
Return
0 on success or -EINVAL on failure
uart_parse_options() #
void Parse serial port baud/parity/bits/flow control.
Parameters
const char *options: pointer to option stringint *baud: pointer to an 'int' variable for the baud rate.int *parity: pointer to an 'int' variable for the parity.int *bits: pointer to an 'int' variable for the number of data bits.int *flow: pointer to an 'int' variable for the flow control character.
Description
uart_parse_options() decodes a string containing the serial console
options. The format of the string is <baud><parity><bits><flow>,
eg: 115200n8r
uart_set_options() #
int setup the serial console parameters
Parameters
struct uart_port *port: pointer to the serial ports uart_port structurestruct console *co: console pointerint baud: baud rateint parity: parity character - 'n' (none), 'o' (odd), 'e' (even)int bits: number of data bitsint flow: flow control character - 'r' (rts)
Description
Locking: Caller must hold console_list_lock in order to serialize early initialization of the serial-console lock.
uart_register_driver() #
int register a driver with the uart core layer
Parameters
struct uart_driver *drv: low level driver structure
Description
Register a uart driver with the core driver. We in turn register with the tty layer, and initialise the core driver per-port state.
We have a proc file in /proc/tty/driver which is named after the normal driver.
drv->port should be NULL, and the per-port structures should be registered
using uart_add_one_port() after this call has succeeded.
Locking: none, Interrupts: enabled
uart_unregister_driver() #
void remove a driver from the uart core layer
Parameters
struct uart_driver *drv: low level driver structure
Description
Remove all references to a driver from the core driver. The low level
driver must have removed all its ports via the uart_remove_one_port() if it
registered them with uart_add_one_port(). (I.e. drv->port is NULL.)
Locking: none, Interrupts: enabled
uart_match_port() #
bool are the two ports equivalent?
Parameters
const struct uart_port *port1: first portconst struct uart_port *port2: second port
Description
This utility function can be used to determine whether two uart_port structures describe the same port.
uart_handle_dcd_change() #
void handle a change of carrier detect state
Parameters
struct uart_port *uport: uart_port structure for the open portbool active: new carrier detect status
Description
Caller must hold uport->lock.
uart_handle_cts_change() #
void handle a change of clear-to-send state
Parameters
struct uart_port *uport: uart_port structure for the open portbool active: new clear-to-send status
Description
Caller must hold uport->lock.
uart_try_toggle_sysrq() #
bool Enables SysRq from serial line
Parameters
struct uart_port *port: uart_port structure where char(s) after BREAK metu8 ch: new character in the sequence after received BREAK
Description
Enables magic SysRq when the required sequence is met on port (see CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE).
Return
false if ch is out of enabling sequence and should be
handled some other way, true if ch was consumed.
uart_port_tx_limited() #
- transmit helper for uart_port with count limiting
Parameters
port: uart portch: variable to store a character to be written to the HWcount: a limit of characters to sendtx_ready: can HW accept more data functionput_char: function to write a charactertx_done: function to call after the loop is done
Description
This helper transmits characters from the xmit buffer to the hardware using put_char(). It does so until count characters are sent and while tx_ready evaluates to true.
- The expression in macro parameters shall be designed as follows:
- tx_ready: should evaluate to true if the HW can accept more data to
be sent. This parameter can be
true, which means the HW is always ready. - put_char: shall write ch to the device of port.
- tx_done: when the write loop is done, this can perform arbitrary
action before potential invocation of ops->
stop_tx()happens. If the driver does not need to do anything, use e.g. ({}).
- tx_ready: should evaluate to true if the HW can accept more data to
be sent. This parameter can be
For all of them, port->lock is held, interrupts are locally disabled and the expressions must not sleep.
Return
the number of characters in the xmit buffer when done.
uart_port_tx() #
- transmit helper for uart_port
Parameters
port: uart portch: variable to store a character to be written to the HWtx_ready: can HW accept more data functionput_char: function to write a character
Description
See uart_port_tx_limited() for more details.
Other notes #
It is intended some day to drop the 'unused' entries from uart_port, and allow low level drivers to register their own individual uart_port's with the core. This will allow drivers to use uart_port as a pointer to a structure containing both the uart_port entry with their own extensions, thus:
struct my_port {
struct uart_port port;
int my_stuff;
};
Modem control lines via GPIO #
Some helpers are provided in order to set/get modem control lines via GPIO.
mctrl_gpio_set() #
void set gpios according to mctrl state
Parameters
struct mctrl_gpios *gpios: gpios to setunsigned int mctrl: state to set
Description
Set the gpios according to the mctrl state.
mctrl_gpio_to_gpiod() #
struct gpio_desc * obtain gpio_desc of modem line index
Parameters
struct mctrl_gpios *gpios: gpios to look intoenum mctrl_gpio_idx gidx: index of the modem line
Return
the gpio_desc structure associated to the modem line index
mctrl_gpio_get() #
unsigned int update mctrl with the gpios values.
Parameters
struct mctrl_gpios *gpios: gpios to get the info fromunsigned int *mctrl: mctrl to set
Return
modified mctrl (the same value as in mctrl)
Description
Update mctrl with the gpios values.
mctrl_gpio_init() #
struct mctrl_gpios * initialize uart gpios
Parameters
struct uart_port *port: port to initialize gpios forunsigned int idx: index of the gpio in the port's device
Description
This will get the {cts,rts,...}-gpios from device tree if they are present
and request them, set direction etc, and return an allocated structure.
devm_* functions are used, so there's no need to explicitly free.
As this sets up the irq handling, make sure to not handle changes to the
gpio input lines in your driver, too.
mctrl_gpio_enable_ms() #
void enable irqs and handling of changes to the ms lines
Parameters
struct mctrl_gpios *gpios: gpios to enable
mctrl_gpio_disable_ms_sync() #
void disable irqs and handling of changes to the ms lines, and wait for any pending IRQ to be processed
Parameters
struct mctrl_gpios *gpios: gpios to disable
mctrl_gpio_disable_ms_no_sync() #
void disable irqs and handling of changes to the ms lines, and return immediately
Parameters
struct mctrl_gpios *gpios: gpios to disable
ISO7816 Serial Communications
Peios Kernel / Hardware and drivers / Driver development / Serial ports
1. Introduction #
ISO/IEC7816 is a series of standards specifying integrated circuit cards (ICC) also known as smart cards.
2. Hardware-related considerations #
Some CPUs/UARTs (e.g., Microchip AT91) contain a built-in mode capable of handling communication with a smart card.
For these microcontrollers, the Linux driver should be made capable of working in both modes, and proper ioctls (see later) should be made available at user-level to allow switching from one mode to the other, and vice versa.
3. Data Structures Already Available in the Kernel #
The Linux kernel provides the serial_iso7816 structure (see [1]) to handle ISO7816 communications. This data structure is used to set and configure ISO7816 parameters in ioctls.
Any driver for devices capable of working both as RS232 and ISO7816 should implement the iso7816_config callback in the uart_port structure. The serial_core calls iso7816_config to do the device specific part in response to TIOCGISO7816 and TIOCSISO7816 ioctls (see below). The iso7816_config callback receives a pointer to struct serial_iso7816.
4. Usage from user-level #
From user-level, ISO7816 configuration can be get/set using the previous ioctls. For instance, to set ISO7816 you can use the following code:
#include <linux/serial.h> /* Include definition for ISO7816 ioctls: TIOCSISO7816 and TIOCGISO7816 */ #include <sys/ioctl.h> /* Open your specific device (e.g., /dev/mydevice): */ int fd = open ("/dev/mydevice", O_RDWR); if (fd < 0) { /* Error handling. See errno. */ } struct serial_iso7816 iso7816conf; /* Reserved fields as to be zeroed */ memset(&iso7816conf, 0, sizeof(iso7816conf)); /* Enable ISO7816 mode: */ iso7816conf.flags |= SER_ISO7816_ENABLED; /* Select the protocol: */ /* T=0 */ iso7816conf.flags |= SER_ISO7816_T(0); /* or T=1 */ iso7816conf.flags |= SER_ISO7816_T(1); /* Set the guard time: */ iso7816conf.tg = 2; /* Set the clock frequency*/ iso7816conf.clk = 3571200; /* Set transmission factors: */ iso7816conf.sc_fi = 372; iso7816conf.sc_di = 1; if (ioctl(fd_usart, TIOCSISO7816, &iso7816conf) < 0) { /* Error handling. See errno. */ } /* Use read() and write() syscalls here... */ /* Close the device when finished: */ if (close (fd) < 0) { /* Error handling. See errno. */ }
5. References #
[1] include/uapi/linux/serial.h
RS485 Serial Communications
Peios Kernel / Hardware and drivers / Driver development / Serial ports
1. Introduction #
EIA-485, also known as TIA/EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems. This standard is widely used for communications in industrial automation because it can be used effectively over long distances and in electrically noisy environments.
2. Hardware-related Considerations #
Some CPUs/UARTs (e.g., Atmel AT91 or 16C950 UART) contain a built-in half-duplex mode capable of automatically controlling line direction by toggling RTS or DTR signals. That can be used to control external half-duplex hardware like an RS485 transceiver or any RS232-connected half-duplex devices like some modems.
For these microcontrollers, the Linux driver should be made capable of working in both modes, and proper ioctls (see later) should be made available at user-level to allow switching from one mode to the other, and vice versa.
3. Data Structures Already Available in the Kernel #
The Linux kernel provides the struct serial_rs485 to handle RS485 communications. This data structure is used to set and configure RS485 parameters in the platform data and in ioctls.
The device tree can also provide RS485 boot time parameters 1. The serial core fills the struct serial_rs485 from the values given by the device tree when the driver calls uart_get_rs485_mode().
Any driver for devices capable of working both as RS232 and RS485 should implement the
rs485_configcallback and providers485_supportedin thestruct uart_port. The serial core callsrs485_configto do the device specific part in response to TIOCSRS485 ioctl (see below). Thers485_configcallback receives a pointer to a sanitizated struct serial_rs485. The struct serial_rs485 userspace provides is sanitized before callingrs485_configusingrs485_supportedthat indicates what RS485 features the driver supports for thestruct uart_port. TIOCGRS485 ioctl can be used to read back the struct serial_rs485 matching to the current configuration.
struct serial_rs485 #
serial interface for controlling RS485 settings.
Definition
;
Members
flags: RS485 feature flags.delay_rts_before_send: Delay before send (milliseconds).delay_rts_after_send: Delay after send (milliseconds).{unnamed_union}: anonymouspadding: Deprecated, use padding0 and padding1 instead. Do not use with addr_recv and addr_dest (due to overlap).{unnamed_struct}: anonymousaddr_recv: Receive filter for RS485 addressing mode (used only whenSER_RS485_ADDR_RECVis set).addr_dest: Destination address for RS485 addressing mode (used only whenSER_RS485_ADDR_DESTis set).padding0: Padding (set to zero).padding1: Padding (set to zero).
Description
Serial interface for controlling RS485 settings on chips with suitable support. Set with TIOCSRS485 and get with TIOCGRS485 if supported by your platform. The set function returns the new state, with any unsupported bits reverted appropriately.
The flag bits are:
SER_RS485_ENABLED- RS485 enabled.SER_RS485_RTS_ON_SEND- Logical level for RTS pin when sending.SER_RS485_RTS_AFTER_SEND- Logical level for RTS pin after sent.SER_RS485_RX_DURING_TX- Full-duplex RS485 line.SER_RS485_TERMINATE_BUS- Enable bus termination (if supported).SER_RS485_ADDRB- Enable RS485 addressing mode.SER_RS485_ADDR_RECV- Receive address filter (enables addr_recv). RequiresSER_RS485_ADDRB.SER_RS485_ADDR_DEST- Destination address (enables addr_dest). RequiresSER_RS485_ADDRB.SER_RS485_MODE_RS422- Enable RS422. RequiresSER_RS485_ENABLED.
4. Usage from user-level #
From user-level, RS485 configuration can be get/set using the previous ioctls. For instance, to set RS485 you can use the following code:
#include <linux/serial.h> /* Include definition for RS485 ioctls: TIOCGRS485 and TIOCSRS485 */ #include <sys/ioctl.h> /* Open your specific device (e.g., /dev/mydevice): */ int fd = open ("/dev/mydevice", O_RDWR); if (fd < 0) { /* Error handling. See errno. */ } struct serial_rs485 rs485conf; /* Enable RS485 mode: */ rs485conf.flags |= SER_RS485_ENABLED; /* Set logical level for RTS pin equal to 1 when sending: */ rs485conf.flags |= SER_RS485_RTS_ON_SEND; /* or, set logical level for RTS pin equal to 0 when sending: */ rs485conf.flags &= ~(SER_RS485_RTS_ON_SEND); /* Set logical level for RTS pin equal to 1 after sending: */ rs485conf.flags |= SER_RS485_RTS_AFTER_SEND; /* or, set logical level for RTS pin equal to 0 after sending: */ rs485conf.flags &= ~(SER_RS485_RTS_AFTER_SEND); /* Set rts delay before send, if needed: */ rs485conf.delay_rts_before_send = ...; /* Set rts delay after send, if needed: */ rs485conf.delay_rts_after_send = ...; /* Set this flag if you want to receive data even while sending data */ rs485conf.flags |= SER_RS485_RX_DURING_TX; if (ioctl (fd, TIOCSRS485, &rs485conf) < 0) { /* Error handling. See errno. */ } /* Use read() and write() syscalls here... */ /* Close the device when finished: */ if (close (fd) < 0) { /* Error handling. See errno. */ }
5. Multipoint Addressing #
The Linux kernel provides addressing mode for multipoint RS-485 serial communications line. The addressing mode is enabled with
SER_RS485_ADDRBflag in struct serial_rs485. The struct serial_rs485 has two additional flags and fields for enabling receive and destination addresses.
Address mode flags:
SER_RS485_ADDRB: Enabled addressing mode (sets also ADDRB in termios).
SER_RS485_ADDR_RECV: Receive (filter) address enabled.
SER_RS485_ADDR_DEST: Set destination address.Address fields (enabled with corresponding
SER_RS485_ADDR_*flag):
addr_recv: Receive address.
addr_dest: Destination address.Once a receive address is set, the communication can occur only with the particular device and other peers are filtered out. It is left up to the receiver side to enforce the filtering. Receive address will be cleared if
SER_RS485_ADDR_RECVis not set.Note: not all devices supporting RS485 support multipoint addressing.