Serial communication learning notes under Linux

xiaoxiao2021-03-18  226

Serial communication learning notes under Linux

Author: Jiang Jiang

E-mail: jznsmail@tom.com

QQ: 457283

BLOG: http://blog.9cbs.net/jznsmail

First, what is serial communication

Serial port communication refers to serial transfer between computer hosts and peripherals and data between host systems and host systems. When using serial port communication, each character transmitted and received is actually a one-time transfer, each bit of 1 or 0.

Second, the classification of serial port communication

Serial communication can be divided into two categories of synchronous communications and asynchronous communication. The synchronous communication is to realize the transmission and reception of data in accordance with the software identification synchronization character, asynchronous communication is a communication method using the resynchronization technique using characters.

2.1 Synchronous Communication

Synchronous communication is a communication mode of continuous serial transfer data. One communication is only transmitted. The information frame here is different from the character frames in asynchronous communication, which typically contains several data characters. Figure:

Single synchronization character frame structure

--- ------ ------- ---- ----- ------ ------ - -------

| Synchronization | Data | Data | Data | ... | Data | CRC1 | CRC2 |

| Character | Character 1 | Character 2 | Character 3 | | Character N | | |

--- ------ ------- ---- ----- ------ ------ - -------

Double synchronization character frame structure

--- ------ ------ ------ ---------- ------- ------

| Synchronization | Synchronization | Data | Data | ... | Data | CRC1 | CRC2 |

| Character 1 | Character 2 | Character 1 | Character 2 | | Character N | | |

--- ------ ------ ------ ---------- ------- ------

They consist of synchronization characters, data characters, and check character (CRC). The sync character is located in the frame opening and is used to confirm the beginning of the data character. The data character is after the synchronization character, the number is not limited, determined by the data block length required; the check character has 1 to 2, and the receiving end is used to correct the correctability of the connected character sequence.

The disadvantage of synchronous communication is that the sending clock and the receiving clock remain strictly synchronized.

2.2 Asynchronous communication

In asynchronous communication, data is usually transmitted in character or bytes in units of characters. The character frame is transmitted by the sender, and is received by the transmission line by the transmission line. The transmitting end and the receiving end can control the transmission and reception of the data from the respective clocks, which are independent of each other and are not synchronized with each other.

When the receiving end detects the low level logic "0" (ie, the character frame start bit) transmitted on the transmission line, it is determined that the sender has begun to send data, and whenever the receiving end receives the stop bit in the character frame, it will know. One frame of characters have been sent.

There are two important indicators in asynchronous passages: character frame format and baud rate.

(1) Character frame, consist of starting position, data bit, parity bit, and stop bit. Figure:

No vacancy character frame

- - - - - - - - - - - -

| D7 | 0/1 | 1 | 0 | D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | 0/1 | 1 | 0 | D0 | D1 | - - --- - - - - - - - -

The parity stopped parked

Check check stop

Position

Free level character frame

- - - - - - - - - - - -

| 1 | 0 | D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | 0/1 | 1 | 1 | 1 | 1 | 0 | D0 |

- - - - - - - - - - - -

Empty parity

Idle check stop

Position

1. Start bit: The start of the character frame, accounting for 1 bit, always is a logic 0 level, and is used to indicate the transmitting device to start sending one frame information.

2. Data Bits: After keeping up in the start bit, it can be set to 5 bits, 6, 7, 8 bits, and low in the previous high.

3. Parity bit: After the data bits, only one digit is used to indicate that the serial communication is used to use the odd calibration or even check.

(2) Baud rate, the baud rate is the number of binary digits per second, and the unit is B / s.

The advantage of asynchronous communication is that it is not necessary to transfer the same step pulse, and the length of the character frame is not limited. The disadvantage is that the transmission rate of the valid data is reduced in the character frame because the start bit and stop bit is included.

Third, what is RS-232

RS-232-C Interface (also known as EIA RS-232-C) It is a standard for serial communication using the US Electronics Industry Association (EIA) combined with Bell system, modem manufacturers and computer terminal manufacturers in 1970 . Its full name is "Data Terminal Device (DTE) and Data Communication Equipment (DCE) Standards" This standard specified that a 25 foot DB25 connector is used, each of the connector The signal content of the foot is specified, and the level of various signals is also specified. The transmission distance should be 50 feet in the case where the symbol distortion is less than 4%.

Fourth, computer serial port

Leading number

1 ground

2 TXD output

3 RXD input

4 RTS request send

5 CTS request reception

6 DSR data sequence ready

7 GND logic

8 DCD data load detection

9 reserved

10 reserved

11 undefined

12 backup DCD

13 backup CTS

14 backup TXD

15 transmission clock

16 backup rxd

17 receive clock

18 undefined

19 backup RTS

20 DTR data terminal ready

21 signal quality detection

22 alarm detection

23 Data rate selection

24 transmission clock

25 undefined

V. Full-duplex and half-duplex

1. Full-duplex, indicating that the machine can send data at the same time and can receive data, there are two separate data channels (one for sending, one for receiving)

2. Half duplex, indicating that the machine cannot receive data while sending data.

Six, traffic control

1. Using software methods

Use special characters to mark the start and end of the data stream, such as XON, DC1, and Octa 021 to start, with X0FF, DC3, and Octa 023 to end.

2. Using hardware methods

Use RS232's CTS and RTS signals instead of special character control. When the recipient is ready to receive more data, set the CTS to 0, and vice versa set to 1. When the corresponding sender is ready to send data, the RTS is set to 0.

VII, serial port

The serial port is accessible through the device file as all devices under Linux.

7.1 Open the serial port

Under the Linux system, the serial device is opened through the Open function, but it should be noted that the general user is not permission access device file, requiring access to the open serial device to general user accessible permissions.

Open function

head File

#include

#include

#include

Function prototype

INT Open (const char * pathname, int OFLAG, ... / *, MODE_T MODE * /);

parameter

Const char * pathname - to open the file name, such as / dev / ttys0

INT OFLAG - File Open mode, available logo as follows:

O_RDONLY Opens the file in read-only mode

O_Wronly opens only files

O_RDWR opens files in reading and writing

O_Append is added to the end of the file

O_CREATE If the file does not exist, the file is generated, using this flag to set the access rights mode_t

O_EXCL Specifies the flag and specifies the O_CREATE flag. If there is an open file, it will generate an error.

O_TRUNC If the file exists and successfully writes or only writes, clear all the contents, make the file length becomes 0

O_NOCTTY If an end device is turned on, this program does not become a control terminal corresponding to this port. If there is no such sign, any input, such as a keyboard abort signal, etc., will affect the process.

O_nonblock This flag is similar to the early O_ndlay flags. The program does not care about the status of the DCD signal line. If the flag is specified, the process will continue to sleep until the DCD signal line is 0.

O_Sync Writing I / O

return value

Successfully returns a file descriptor, if the failed returns -1

For example: open / dev / ttys0 devices in a readable write

INT fd; / * file descriptor * /

FD = Open ("/ dev / ttys0", o_rdwr | 0_nOctty | o_nonblock);

7.2 Close the serial port

Turn off the serial port by close function under the Linux system

Close function

head File

#include

Function prototype

INT Close (int filedes);

parameter

INT filedes - file descriptor

return value

Successfully returned 0, otherwise returns -1

For example: Closing the open serial device FD

int Ret; / * Return to the logo, used to determine if it is normal shutdown device * /

RET = Close (FD);

7.3 write serial port

Writing serial port is done by Write functions

Write function

head File

#include

Function prototype

SSIZE_T WRITE (Int Filedes, Const Void * Buff, Size_t Nbytes);

parameter

INT filedes - file descriptor

Const void * buff - Data buffer in writing data

SIZE_T NBYTES - Write data bytes

return value

SSIZE_T - Returns the number of bytes written to the data, which is usually equal to NBYTES, if the write failed returns -1

For example: send initialization command to terminal devices

INT n = 0; / * Write bytes * /

N = Write (FD, "ATZ / R", 4);

IF (n == -1)

{

FPRINTF (stderr, "wirte atz command error ./N");

}

7.4 read serial port

The reading serial port is done through the READ function.

Read function

head File

#include

Function prototype

SSIZE_T Read (int filedes, void * buff, size_t nbytes);

parameter

INT filedes - file descriptor

Void * Buff - Store data buffer read data

SIZE_T NBYTES - Number of bytes that need to be read

return value

SSIZE_T - Successfully Read the number of bytes returned to read, otherwise returns -1

Note that when the serial port is read, if the RAW mode is used, each READ system call will return the number of bytes present in the current serial input buffer. If there is no data, it will be uniformly blocked to a character to reach or the interval clock expire, or an error occurs. If you want the read function to return immediately when there is no data, you can use the FCNTL function to set the file access attribute. E.g:

Fcntl (fd, f_setfl, fndelay);

After this is set, when there is no readable data, the READ function returns to 0 immediately.

The general state can be set back by Fcntl (FD, F_SETFL, 0).

For example: read 5 bytes of response data from the terminal

INT NREAD; / * Number of bytes read from the terminal * /

Char buffer [256]; / * Receive buffer * /

NREAD = Read (FD, Buffer, 5);

IF (NREAD == -1)

{

FPRINTF (stderr, "read answer message error ./N");

}

Eight, terminal configuration

8.1 POSIX Terminal Interface

Most systems support POSIX terminal interfaces, and the POSIX terminal is controlled by a Termios structure, which is defined in the Termios.h file.

Termios structure

Struct termios

{

Tcflag_t c_iflag; / * Enter option flag * /

Tcflag_t c_oflag; / * Output Options Sign * /

Tcflag_t c_cflag; / * Control Options Sign * /

TCFLAG_T C_LFLAG; / * Local Option Sign * /

CC_T C_CC [NCCS]; / * Control Features * /

}

C_IFLAG member

Flag Description

IGNBRK ignores the BREAK status in the input

BRKINT If IGNBRK is set, BREAK will be ignored. If there is no setting, but set BRKINT, BREAK will enable the input and output queue to be refreshed, if the terminal is a control terminal of a foreground process group, all processes in this process group will receive a sigint signal. If BRKINT is not set to both IGnBrk, Break will be considered a nul synonym, unless set of PARMRK, this case is considered sequence / 377/0 / 0ignPar ignore errors and parity errors

PARMRK If IGNPAR is not set, insert / 377/0 before a parity error or erroneous characters. If neither IGnPar is set, PARMRK is not set, and all parity errors or erroneous characters are treated as / 0.

INPCK Enables input parity test.

Istrip removes the eighth place.

InLCR translate the input NL to Cr.

IGNCR ignores the Enter in the input.

ICRNL translates the entered Enter Translate into new line characters (unless IGNCR) is set.

IUCLC (not posix) will map uppercase letters in the input to lowercase letters.

IXON enables output XON / XOFF stream control

IXANY (not posix.1; xsi) allows any characters to restart the output.

IXOFF enabled input XON / XOFF stream control

IMAXBEL (not posix) is ringing when the input queue is full. Linux does not implement this bit, always deemed it to be set.

C_OFLAG member

Flag Description

OPOST enables specific outputs to be customized.

OLCUC (not posted) will map the lowercase letters in the output to uppercase letters.

ONLCR (XSI) maps the new line of the output to the Enter - Renewal

OCRNL maps the carriage return in the output to a new line.

ONOCR is not output from the 0th column.

ONLRET does not output Enter.

Ofill transmits filling characters as delay.

Fill characters are ASCII DEL (0177). If the fill word is not set, it is ASCII NUL.

NLDLY new row delay mask. The value is NL0 and NL1.

CRDLY Enter the latency mask. The value is CR0, CR1, CR2 or CR3.

TabDLY horizontal jump delay mask. The value is Tab0, Tab1, Tab2, Tab3 (or XTABS). Take the value of Tab3, ie XTABS, the extension jump is spaced (8 spaces per jumper).

BSDLY Enter the latency mask. The value is BS0 or BS1. (Never been implemented)

VTDLY vertical jumping mask. The value is VT0 or VT1.

Ffdly inputs the table delay mask. The value is FF0 or FF1.

C_cflag member

Flag Description

CBAUD (not a POSIX) baud rate mask (4 1).

The baud rate mask (1 bit) extended in CBaudEX is included in CBAUD.

CSIZE character length mask. The value is CS5, CS6, CS7 or CS8.

CStopb sets two stop bits.

CREAD opens the recipient.

PARENB allows the output to generate parity and the patetened parity. PARODD input and output are odd calibration

HUPCL reduces the Modem control line after closing the device at the last process.

Clocal ignores the Modem control line.

Loblk (not posted) is blocked from a non-current shell layer (for SH1).

CIBAUD is a mask of the input speed of the POSIX. The value of CIBAUD is the same as the CBAUD, and the left is the IBSHIFT bit.

Crtscts Enable RTS / CTS (hardware) control flow.

C_LFlag member

Flag Description

ISIG generates a corresponding signal when receiving character INTR, QUIT, SUSP, or DSUSP.

Xcase (not supported under Linux) If ICANON is set at the same time, the terminal is only capitalized. The input is converted to lowercase, except for characters in / prefix. When the output is output, the uppercase characters are prefixed /, and the lowercase characters are converted into capital.

Echo reflects the input character.

Echoe If ICANON is set up, the character ERASE erases the previous input character, and werase erases the previous word.

Echok If ICANON is set at the same time, the character kill deletes the current line.

Echonl If ICANON is set up, the character NL is returned, even if there is no Echo.

EchoctL (not posix) If ECHO is set, an ASCII control signal other than Tab, NL, START, and STOP is returned to ^ x, where x is a ASCII code than the control signal large 0x40. For example, character 0x08 (BS) is eged into ^ h.

Echoprt (not posix) If ICANON and IECHO are set up, characters are printed while deleting.

Echoke (not posix) If ICANON is set up, you will delete each character in a row when you return KILL, just like the Echoe and Echorpt.

Defecho (not posted) is only elected when a process is read.

FLUSHO (not posted; Linux does not support) output is refreshed. This flag can be turned on and off by typing character discard.

NOFLSH prohibits refreshing input and output queues when Sigint, SIGQUIT, and SIGSUSP signals are generated.

TOSTOP sends a sigttou signal to the background process group attempt to write the control terminal.

Pendin (not Posix; Linux does not support) When you read a character, all characters in the input queue are reset. (Bash uses him to handle Typeahead).

IEXTEN enables customized input processing. This flag must be used simultaneously with Icanon to explain the special characters EOL2, LNEXT, REPRINT, and Werase, the IuCLC flag is valid.

C_CC array member

Flag Description

VINTR (003, ETX, Ctrl-C, OR Also 0177, Del, Rubout) interrupt characters. Send a sigint signal. When ISIG is set, it can be identified and no longer input. Vquit (034, FS, Ctrl- /) exit characters. Send a sigquit signal. When ISIG is set, it can be identified and no longer input.

Verase (0177, Del, Rubout, OR 010, BS, Ctrl-h, or Also #) deletes characters. Delete the previous character, but does not delete an EOF or lead. When ICANON is set, it can be identified and no longer used as input.

VKILL (025, NAK, CTRL-U, OR CTRL-X, or Also @) terminates characters. Delete input from the top EOF or lead. When ICANON is set, it can be identified and no longer used as input.

VEOF (004, EOT, CTRL-D) file tail character. More precisely, this character makes the content in the TTY buffer are sent to the user program waiting for the input without having to wait until EOL. If it is the first character, then the user program's read () will return 0, indicating that EOF is read. When ICANON is set, it can be identified and no longer used as input.

VMIN is not a minimum number of characters read by the CANONICAL mode. Veol (0, NUL) attached line character. It can be identified when Icanon is set. VTIME is non-Canonical mode delay at a very in seconds. Veol2 (Not in Posix; 0, NUL) is another line of tail characters. It can be identified when Icanon is set.

Veol (0, NUL) attached line character. It can be identified when Icanon is set.

VTIME is non-Canonical mode delay at a very in seconds.

Veol2 (Not in Posix; 0, NUL) is another line of tail characters. It can be identified when Icanon is set.

Vswtch (Not In Posix; Not Supported Under Linux; 0, NUL) Switch Character. (Use only for SHL.)

VStart (021, DC1, CTRL-Q) begins character. Resume output being aborted by the STOP character. When IXON is set, it can be identified and no longer input.

VStop (023, DC3, CTRL-S) stops characters. Stop output until you type the Start character. When IXON is set, it can be identified and no longer input.

VSUSP (032, SUB, CTRL-Z) hangs the character. Send a SIGTSTP signal. When ISIG is set, it can be identified and no longer input.

VDSUSP (NOT IN POSIX; NOT Supported Under Linux; 031, EM, CTRL-Y) delay suspension signal. When the user program is read this character, the SigTSTP signal is sent. When IEXTEN and ISIG are set, and the system can be identified when the system supports job management, and no longer be transmitted as input.

The next one on the field of VLNext (Not in Posix; 026, Syn, Ctrl-V). Quote the next input character, cancel any special meaning of it. When IEXTEN is set, it can be identified and no longer input.

Vwerase (Not in Posix; 027, ETB, CTRL-W) deletes the word. When ICANON and IEXTEN are set, it can be identified and no longer input.

Vreprint (not in posix; 022, dc2, ctrl-r) re-outputs unread characters. When ICANON and IEXTEN are set, it can be identified and no longer input. Vdiscard (Not In Posix; Not Supported Under Linux; 017, Si, Ctrl-O) Switch: Start / End Discard Unfinished Output. When IEXTEN is set, it can be identified and no longer input.

VSTATUS (Not in Posix; Not Supported Under Linux; Status Request: 024, DC4, Ctrl-T).

8.2 Setting the baud rate

For baud rate settings are usually done using the cfsetospeed and cfsetispeed functions. Get baud rate information is done by cfgetispeed and cfgetospeed functions.

Cfsetospeed function

head File:

#include

Function prototype:

Int cfsetospeed (Struct Termios * Termptr, Speed_t Speed);

parameter:

Struct Termios * Termptr - Pointer to the Termios structure

Speed_t speted - the output baud rate required to set

return value:

If you successfully return 0, otherwise returns -1

Cfsetispeed function

head File:

#include

Function prototype:

INT CFsetispeed (Struct Termios * Termptr, Speed_t speed);

parameter:

Struct Termios * Termptr - Pointer to the Termios structure

Speed_t speed - the input baud rate required to set

return value:

If you successfully return 0, otherwise returns -1

Cfgetospeed function

head File:

#include

Function prototype:

Speed_t cfgetospeed (const struct termios * termptr);

parameter:

Const struct Termios - Pointer to Termios

return value:

Return output baud rate

Cfgetispeed function

head File:

#include

Function prototype:

Speed_t cfgetispeed (const struct termios * termptr);

parameter:

Const struct Termios * Termptr - Pointer to Termios Structure

return value:

Return the input baud rate

Porter rate constant:

CBAUD mask

B0 0 baud

B50 50 baud

B75 75 baud

B110 100 baud

B134 134 baud

B150 150 baud

B200 200 Potter

B300 300 baud

B600 600 baud

B1200 1200 baud

B1800 1800 baud

B2400 2400 baud

B9600 9600 Potter

B19200 19200 Potter

B38400 38400 Potter

B57600 57600 Potter

B115200 115200 baud

8.3 Setting the character size

Setting the size of the character is implemented by setting the C_CFLAG flag.

E.g:

Option.c_cflag & = ~ csize; Option.c_cflag | = CS7;

8.4 Set parity

For parity, it is necessary to manually set, and the common setting is as follows:

NO Parity (8n1):

Options.c_cflag & = ~ Parenb

Options.c_cflag & = ~ cstopb

Options.c_cflag & = ~ csize;

Options.c_cflag | = CS8;

Even Parity (7e1):

Options.c_cflag | = Parenb

Options.c_cflag & = ~ PARODD

Options.c_cflag & = ~ cstopb

Options.c_cflag & = ~ csize;

Options.c_cflag | = CS7;

ODD PARITY (7O1):

Options.c_cflag | = Parenb

Options.c_cflag | = Parodd

Options.c_cflag & = ~ cstopb

Options.c_cflag & = ~ csize;

Options.c_cflag | = CS7;

Space Parity Is Setup The Same As No Parity:

Options.c_cflag & = ~ Parenb

Options.c_cflag & = ~ cstopb

Options.c_cflag & = ~ csize;

Options.c_cflag | = CS8;

8.5 Get and set the terminal attribute

Setting up and getting the terminal control attribute is done by the two functions of Tcgetattr and TcSetattr

Tcgetattr function

head File:

#include

Function prototype:

Int tcgetattr (int filedes, struct termios * termptr);

parameter:

INT filedes - file descriptor

Struct Termiso * Termptr - points to the pointer of the Termios structure,

return value:

If you successfully return 0, otherwise returns -1

TCSetattr function

head File:

#include

Function prototype:

INT TCSetattr (int filedes, int Opt, const struct termios * termptr);

parameter:

INT filedes - file descriptor

INT OPT - option value, can be one of the three values ​​below

Tcsanow - change attributes for unequal data transmission

TCSADRAIN - Waiting for all data transfer ends to change attributes

TCSAFLUSH - Clear input Output buffer and set attributes

Const struct Termios * Termptr - points to the pointer of the Termios structure,

return value:

Successfully returned 0, otherwise returns -1

Nine, common settings

9.1 Setting the specification mode

The specification mode is a row-oriented input method, and the input character is placed in a buffer that can be edited with the user, and it ends directly to the recovery or wrap symbol.

Can be set as follows

Option.c_lflag | = (Icanon | Echo | Echoe);

9.2 Set the original input mode

The original input mode is not processed. When the data is received, the input character is transmitted immediately after they are received, and when using the original input mode, you can generally select the cancellation of Icanon, Echo, Echoe, and ISIG options. E.g:

Option.c_lflag & = ~ (Icanon | Echo | Echoe);

9.3 Setting the input parity option

When the parity in the c_cflag is activated, the patetened check should be activated. The symbols associated with it have INPCK, IGNPAR, PARMRK, and ISTRIP. Testing and removing parity bits are typically activated by selecting INPCK and ISTRIP.

E.g:

Option.c_iflag | = (INPCK | Istrip);

9.4 Setting up software control flow

Software control flows through IXON, IXOFF, and IXANY flags

E.g:

Option.c_iflag | = (ixon | ixoff | ixany);

9.5 Select Preprocessing Output

Set the pre-processing output by the OPOST flag

E.g:

Option.c_oflag | = OPOST;

9.6 Select the original data output

The output of the original data is set by setting c_oflag Opost flags.

E.g:

Option.c_oflag & = ~ opost;

9.7 Setting up Soft Flow Control Character

Soft flow control characters are set by VStart and VStop in the C_CC array. In general, they should be set up in the city DC1 (021 eight into system) and DC3 (023 eight-on-system), indicating the XON and XOFF characters of the ASCII code, respectively.

9.8 Setting up timeout

The VMIN in the c_cc array specifies the number of characters read, if set to 0, then VTIME specifies the waiting time for reading each character. VTIME is a timeout time specified in 1/10 seconds. If the VTIME is set to 0, the port does not use Open or Fcntl to Nonblock, then the READ operation will block the uncertain time.

Ten, reference materials

1. "Serial Programming Guide for POSIX OPERATING SYSTEMS" 5th Edition Michael R.Sweet

2. "Getting Started under Linux" Zuo Jin

3. "Advanced Programming in The Unix Environment" W.Richard Stevens

4. "Linux Serial Programming HOWTO"

5. "Unix Systems Programming" Kay A.Robbins & Steven Robbins

6. "Linux Programming By Example" Arnold Robbins

7. "Linux Programmer's Manual"

转载请注明原文地址:https://www.9cbs.com/read-129916.html

New Post(0)