Detailed description of Serial Communication Development in Linux [reprint]

Source: Internet
Author: User

Detailed description of Serial Communication Development in Linux [reprint]
The serial port is a common interface for computers. It has a wide range of applications, such as a few connection lines and simple communication. Commonly used serial port is RS-232-C interface (also known as EIA RS-232-C) it was in 1970 by the American Association of Electronic Industry (EIA) the serial communication standard jointly developed by Bell systems, modem manufacturers, and computer terminal manufacturers. Serial communication refers to data transmission by bit in a computer. Serial Communication is widely used. It is also frequently used in the development of embedded systems.

Linux accesses all devices through device files. The same is true for the serial port. To access the serial port, you only need to open the file of the device to operate the serial port device. In Linux, each serial device has a device file associated with it. The device file is located under the/dev directory of the system. For example, in Linux,/ttys0 and/ttys1 indicate Serial 1 and Serial 2 respectively. The following describes how to use serial ports in Linux:

1. header files required for serial port operations

# Include <stdio. h>/* standard input/output definition */

# Include <stdlib. h>/* standard function library definition */

# Include <unistd. h>/* UNIX standard function definition */

# Include <sys/types. h>

# Include <sys/STAT. h>

# Include <fcntl. h>/* file control definition */

# Include <termios. h>/* POSIX terminal control definition */

# Include <errno. h>/* Error Code definition */

# Include <string. h>/* string function */

2. Set the baud rate for Serial Communication

The baud rate is defined in <ASM/termbits. h>, which is included in the header file <termios. h>.

The common baud rate constants are as follows:

B0 ------- à 0 b1800 ------- à 1800

B50 ----- à 50 b2400 ------ à 2400

B75 ----- à 75 b4800 ------ à 4800

B110 ---- à 110 b9600 ------ à 9600

B134 ---- à 134. 5 b19200 ----- à 19200

B200 ---- à 200 b38400 ------ à 38400

B300 ---- à 300 b57600 ------ à 57600

B600 ---- à 600 b76800 ------ à 76800

B1200 --- à 1200 b115200 ----- à 115200

Assume that you want to set the baud rate of communication in the program. You can use the cfsetispeed () and cfsetospeed () functions to obtain the baud rate information through the cfgetispeed () and cfgetospeed () functions. For example, you can specify the baud rate of serial communication as follows:

# Include <stdio. h> // header file Definition

........

........

.......

Struct termios OPT;/* defines the pointer to the termios structure type opt */

 

****************/

Cfsetispeed (& OPT, b9600);/* specify the input baud rate, 9600bps */

Cfsetospeed (& OPT, b9600);/* specify the output baud rate, 9600bps */

/*************************************** *********/

.........

..........

In general, the input and output baud rates should be consistent.

3. Serial Port attribute Configuration

In the program, it is easy to configure the properties of the serial port, which are defined in the struct termios. To use this struct in a program, the <termbits. h> file must be included. This header file defines the struct termios. The struct is defined as follows:

# Define NCCs 19

Struct termios {

Tcflag_t c_iflag;/* input parameter */

Tcflag_t c_oflag;/* output parameter */

Tcflag_t c_cflag;/* Control Parameter */

Tcflag_t c_ispeed;/* enter the baud rate */

Tcflag_t c_ospeed;/* output baud rate */

Cc_t c_line;/* Line Control */

Cc_t c_cc [NCCs];/* control character */

};

The member c_line is not used in the POSIX (Portable Operating System Interface for UNIX) system. For systems that support POSIX terminal interfaces, two important functions are used to set and obtain port properties:

(1). Int tcsetattr (int fd, int opt_de, * PTR)

This function is used to set terminal control attributes. Its parameters are described as follows:

L FD: file descriptor to be operated

L opt_de: option value. Three options are available for selection:

Tcsanow: changes the attributes immediately after data transmission is completed.

Tcsadrain: the attribute is changed only after all data transmission ends.

Tcsaflush: the attribute is changed only when the input and output buffer is cleared.

L * PTR: pointer to the termios Structure

Function return value: 0 is returned for success, and-1 is returned for failure.

(2). Int tcgetattr (int fd, * PTR)

This function is used to obtain terminal control attributes. It assigns the default settings of the serial port to the data structure of termios. The parameters are described as follows:

L FD: file descriptor to be operated

L * PTR: pointer to the termios Structure

Function return value: 0 is returned for success, and-1 is returned for failure.

4. Open the serial port

As mentioned above, serial port access in Linux is performed in the form of a device file, so opening a serial port is also an operation to open a file. The function prototype can be as follows:

Int open ("de_name", int open_status)

Parameter description:

(1). de_name: name of the device file to be opened

For example, to enable Serial Port 1, it is/dev/ttys0.

(2). open_status: file opening mode. The following file opening mode can be used:

L o_rdonly: open a file in read-only mode

L o_wronly: open the file in write-only mode

L o_rdwr: open a file in read/write mode

L o_append: added to the end of the file when writing data

L o_create: this file is generated if the file does not exist. To use this flag, you need to set the access limit mode_t.

L o_excl: specifies this flag and specifies the o_create flag. If the opened file exists, an error occurs.

L o_trunc: if the file exists and is successfully opened in write or write-only mode, all content of the file will be cleared, and the file length will be changed to 0.

L o_noctty: If a terminal device is opened, this program will not be the control terminal corresponding to this port. If this flag is not displayed, any input, such as the keyboard stop signal, will affect the process.

L o_nonblock: this flag is similar to the o_ndelay flag used earlier. The program does not care about the status of the DCD signal line. If this flag is specified, the process will remain dormant until the DCD signal line is 0.

Function return value:

The file descriptor is returned successfully. If the file fails,-1 is returned.

For example, if the/dev/ttys0 device is enabled in read/write mode, you can perform the following operations:

# Include <stdio. h> // header file inclusion

......

......

Int FD;/* file descriptor */

FD = open ("/dev/ttys0", o_rdwr | 0_noctty);/* Open the device in read/write mode */

If (FD =-1)

Perror ("can not open serial_port 1/n! ");/* Error prompt when opening fails */

........

........

 

5. Serial Port read operation (acceptor)

Use the OPEN function to open the device file. The function returns a file descriptor (FD) to access the file. The read serial port operation is completed through the READ function. The function prototype is as follows:

Int read (int fd, * buffer, length );

Parameter description:

(1). Int FD: file descriptor

(2). * Buffer: Data Buffer

(3). Length: number of bytes to read

Function return value:

The number of bytes returned when the read operation is successful. If the read operation fails,-1 is returned.

6. Serial Port write operation (sender)

Serial write operations are completed through the write function. The function prototype is as follows:

Write (int fd, * buffer, length );

Parameter description:

(1). FD: file descriptor

(2). * Buffer: data buffer for storing written data

(3). Length: the number of data bytes written to the buffer.

Function return value:

The number of bytes written to the data. The value is usually equal to length. If the write fails,-1 is returned.

For example, send an initialization command to a terminal device.

# Include <stdio. h> // header file inclusion

......

......

 

Int n

Sbuf [] = {hello, this is a serial_port test! /N}; // data to be sent

Int len_send = "sizeof" (sbuf); // The number of bytes in the sending buffer.

N = write (FD, sbuf, len_send); // write the buffer.

If (n =-1)

{

Printf ("wirte sbuf error./N ");

}

......

......

7. Disable the serial port

The operation on the device file is the same as the operation on the common file. After the operation is enabled, you need to close the device file and use the function close () to close the serial port. The function prototype is as follows:

Int close (int fd );

Parameter description:

FD: file descriptor

Function return value:

0 is returned for success, and-1 is returned for failure.

In the subsequent articles, I will provide a serial communication test program for your reference!
 
 
 
 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.