Introduction
The POSIX operating system serial programming guide will teach you how to successfully, efficiently, and conveniently compile serial programs on your UNIX workstation or PC. The POSIX (portable UNIX standard) terminal control function is used in the programming examples provided in each chapter, and can run in IRIX, HP-UX, SunOS, and Solaris as long as a few modifications are made, digital UNIX, Linux, and most other UNIX-like operating systems. The biggest difference in the operating system is the file name used for serial devices and locked files.
This guide consists of the following chapters and appendices:
Chapter 1 basics of serial Programming
Chapter 2 configure serial port
Chapter 3 MODEM communication
Chapter 4 advanced serial Programming
Appendix A RS-232 pins
Appendix B ASCII control flow
----------------------------------------------------------------------
Chapter 1 basics of serial Programming
This chapter describes the serial communication, RS232 and other standards used by most computers, and how to use C Programs to access the serial port.
What is serial communication?
The computer can transmit 1 bit or nbit information (data) each time, and the serial port means to transmit only 1 bit of data each time. Serial Communication includes a variety of network devices: keyboard, mouse, cat, and terminal.
When a single character (character or byte) data is transmitted through a serial port, each bit is 1 or 0.
Most of the data transmission rates of serial ports are expressed as bit/s (BPS) or baud rate (baud), indicating the number of data transmitted between 1 and 0 per second. Back in the Age of computers, 43800 baud was considered to be very fast, but now the RS232 speed of computer applications can reach BAUD (port ). When the baud rate exceeds 1000, you will often see a speed of thousands of Boud, or kbps (such as 9.6 K, K, etc ). if the speed is above 1,000,000, it indicates megabaud or Mbps (for example, 1.5 Mbps ).
When talking about serial devices and ports, they are called data communication devices (DCE) or data terminal devices (DTE ). The difference between them is simple-each pair of transmission signals and reception is exchange. When two DTE or two DCE devices are connected together, a cat-free serial port cable or adapter is used as an exchange signal pair.
What is RS-232?
RS-232 is the electrical industry organization (EIA) developed for serial communication electrification interface standards. RS-232 is actually divided into three levels (a, B, c), each of which has different high and low voltage standards. Fill the most widely used is the RS-232C, which defines the logic 1 voltage in-3 V to-12 V, the logic 0 voltage in + 3 V to + 12 V. RS-232 specifications said these signals in 25 feet after the failure to use. Generally, you can lower the baud rate to further transmit data.
In addition to cable access data, there are other time, status, handshakes:
Table 1-RS-232 pin description
1 Location
2 txd-Data Transmission
3 rxd-receive data
4 RTS-Send request
5 Cts-clear pending
6. DSR-data settings complete
7. Gnd-logical location
8 DCD-Data Carrier Detection
9 Reserved
10 reserved
11 unallocated
12. Backup DCD
13 slave cts
14. Backup txd
15 transmission clock
16 backup rxd
17 receive clock
18 unallocated
19 standby RTS
20 DTR-data terminal preparation
21. Signal Quality Check
22 loop check
23 data rate selection
24 sending clock
25 unallocated
There are two interfaces for standard RS-422 and RS-422. The RS-422 allows up to 1000 feet (300 m) of cable length with lower voltage and different signals ). The RS-574 defines the serial port connection and voltage for 9 pins.
Signal Definition
The RS-232 standard defines different signals in serial port 18. Only six of these are available in UNIX environments.
Gnd-logical location
Logically, it is not a signal, but there is no way to operate on the signal. Basically, it is logically a reference voltage that has made the Electronic Tube aware of those things positive and negative.
Txd-Data Transmission
Txd signal carrier data from your workstation to a computer or device (such as a cat) at the other end ). A high level represents 1, and an empty level represents 0.
Rxd-receive data
The rxd carrier signal transmits the computer or device to the workstation. For example, txd indicates 1 and 0 respectively.
DCD-Data Carrier Detection
The DCD signal is received from a computer or other serial cable. A low level indicates that the device is connected to the computer on the signal line. DCD is usually useless.
DTR-data terminal preparation
The DTR signal is that the workstation generates troops to tell the computer or the other end of the device that you are preparing (null) or not preparing (high ). DTR can automatically run when you open the serial port on the workstation.
CTS-clear sending
CTS signals receive data from other serial ports.
A blank level indicates that serial port data has been prepared to be sent from the workstation. CTS is usually used to control the serial data streams from the workstation to the terminal.
RTS-request sending
The TRS Signal Setting low level is used by the workstation to indicate more data to be sent.
For example, CTS and RTS are used to control data streams from workstations to computer devices and serial devices on the other end. Most workstations always set this signal to low.
Asynchronous Communication
When a computer needs to know when serial data is transmitted in, it needs some methods to determine from where the character starts to end and the next starting point. This guide is dedicated to asynchronous serial data processing.
In asynchronous mode, the serial data line remains high until a character is transmitted. The character properties of each character before and after a start bit, one parity bit, and one or more stop bits. The Start bit is usually an empty level and then tells the computer that new serial data is useful. Data is then sent or received at any time, so it is called asynchronous.
Figure 1-Asynchronous Data Transmission
The parity bit is the sum of the Data bit, indicating that the data contains an even number or an odd number of 1. For parity check, the parity bit is 0. If the number of characters in the character is an even number of 0, the parity bit is 0. If the number of values in the data is 1. you may have heard of low-level verification, high-level verification, and no parity. Low check means that the parity bit is all 0, and the high check means that all these bits are 1. No verification indicates that no verification bits are represented or transmitted. The remaining bit is called the stop bit.
It can be 1, 1.5, or 2 to stop bits and their value is 1. the stop bit was used to process the forward and trailing characters for the computer time, but now it is only used to asynchronously interpret the received characters of the computer.
The asynchronous data format is usually "8n1", "7e1", and forward. These represent "8-Bit Data bit, no parity, 1-bit stop bit" and "7-Bit Data bit, even verification, 1-bit stop bit" respectively ".
What is full duplex and semi-ticket?
Full Duplex refers to the ability of a computer to receive and transmit data at the same time-there are two separate data channels (one-in-one ).
Half Duplex means that the computer cannot receive and transmit data at the same time. This usually means that only one channel is used for communication. However, not all RS232 signals are not used. However, it usually means that communication links use other standards instead of RS232. RS232 does not support full duplex operations.
Traffic Control
It is necessary to transmit data streams between two serial ports. This is because the communication connection between the intermediate serial port is restricted. One is the serial port or the other is the storage media. Two methods are commonly used for asynchronous data communication.
The first method is usually called "software" throttling and application-specific characters (Xon or DC1, 021 octal) or stop (xoff or DC3, 023 octal) data streams. These characters are defined in the American Standard ASCII code. Although these codes are useful for transmitting text information, they are not used when there is no special program conversion.
The second method is known as the "hardware" control flow, where RS-232CTS and RTS signals are used to replace special characters. The receiver sets CTS to low voltage when it is preparing to accept more data. Similarly, when it is not yet ready to transmit other data, the transmitter sets RTS to low level. Because the hardware traffic control uses a group of separated signals, it is faster than the soft traffic control, and it also needs to send and receive multiple confidence to do the same thing. CTS/RTS Throttling is not supported by all hardware and operating systems.
What is interruption?
Generally, a received or transmitted data signal is kept at a high level to know a new character transmission. If the signal goes down to the low level for a long time, usually 1/4 seconds or 1/2 seconds, it can be said that an interruption occurs.
An interruption is sometimes used to restart a communication line or change the operating system's communication mode, such as a cat. Chapter 3 modem covers more advanced applications.
Synchronous Communication
Unlike asynchronous communication, synchronous communication is a constant data stream. To read online data, the computer must provide or receive a synchronization clock and send and receive synchronization.
Even in this way, the computer must mark the start data in some way. The most common practice is to use a Data Protocol package, such as serial Data Link Control (SDLC) or high-speed data link control (HDLC ).
Each Protocol defines a specific bit sequence to indicate the start and end of a packet. Each Protocol also defines a bit sequence, which is used when there is no data; these sequences allow the computer to start viewing the starting data packets.
Because the synchronization protocol does not use each character synchronization bit, it generally provides at least 25% improvement over asynchronous communication, and is more suitable for remote networks and configuring more serial ports.
Despite the high speed advantage of synchronous communication, most RS-232 hardware is not supported because additional hardware and software are required.
Access to a serial port
Like all devices, Unix provides device files connected to serial ports. To access the serial port, you only need to open these corresponding device files. Each serial port has one or more Device Files (the files are in the/dev directory) on the UNIX system:
Table 2-serial port and Device Files
System port1 prot2
IRIX/dev/ttyf1/dev/ttyf2
HP-UX/dev/FIG/dev/tty2p0
Solaris/SunOS/dev/ttya/dev/ttyb
Linux/dev/ttys0/dev/ttys1
Digital UNIX/dev/tty01/dev/tty02
Open a serial port
Because a serial port is a file, the open () function is used to access it. One problem is that common users of UNIX devices cannot access files. The workspace includes interface permissions to files. Run your program as root, or set the user name of the program so that normal users can run the device files.
Now we assume that the file can be used by all users. This code opens the serial port 1 in the IRIX operating system:
Listing 1-open the serial port
# Include/* standard input/output definition */
# Include/* string function definition */
# Include/* UNIX standard function definition */
# Include/* file control definition */
# Include/* Definition of error count */
# Include/* POSIX terminal control definition */
/** 'Open _ port () '-open the serial port 1. ** the returned file description is successful or-1 indicates an error. */
Int open_port (void ){
Int FD;/* file description port definition */
FD = open ("/dev/ttyf1", o_rdwr | o_noctty | o_ndelay );
If (FD =-1 ){
/** The port cannot be opened. */
Perror ("open_port: Unable to open/dev/ttyf1 -");
}
Else
Fcntl (FD, f_setfl, 0 );
Return (FD );
}
For other operating systems, the corresponding device file name is required, but other codes are the same.
Open Operation
You will find that when you open the device file, we usually use two tags except the read + write mode:
FD = open ("/dev/ttyf1", o_rdwr | o_noctty | o_ndelay );
The o_noctty flag tells the UNIX program that it does not want to be the port controlled by the "control terminal". If you cannot explicitly state this port, any input (such as the keyboard interrupt signal) will affect your program. Programs such as Getty (1 m/8) apply this feature when logging on to the program, but a user program usually does not want this problem.
The o_ndelay flag tells the UNIX program not to care about the DCD signal line status-whether other ports are running or not. If this label is not specified, your program will stop when the DCD signal line is low.
Write Data to Port
Writing data to the port is simple-as long as the application write () System Call Back sends data to it:
N = write (FD, "atz/R", 4 );
If (n <0)
Fputs ("write () of 4 bytes failed! /N ", stderr );
The Write function returns the bitwise value or-1 in case of an error. Generally, this error only occurs when a modem or data connection loses the data carrier detection line and you will run to EIO. This situation will be maintained until you release the port.
Read Port Data
Reading port data is troublesome. When you operate this port in raw data mode, each read () system call back will return the serial port input cache actually provides no matter how many characters. If no character is available, the call back will be blocked (waiting) until the character enters, the timer at an interval expires, or an error is sent. The READ function will return immediately using the following code:
Fcntl (FD, f_setfl, fndelay );
The fndelay option enables the READ function to return 0 when no character is on the port. The storage is normal (BLOCKED), and fcntl () is called back without the fndelay option ():
Fcntl (FD, f_setfl, 0 );
The same application opens the serial port in the o_ndelay operation option.
Close serial port
Close the serial port and use close to call the system:
Close (FD );
When a serial port is closed, the DTr signal is set to a low level, which suspends the modulation and demodulation.
Chapter 1 (to be continued)
Chapter 2 configure serial port
This chapter discusses how to configure the serial port to use the POSIX Terminal interface from C.
POSIX Terminal interface
Most systems support POSIX terminal (string) interfaces to change parameters such as baud rate, character size, and so on. First, you need to include the header file <termios. h>. This file defines the terminal control structure and POSIX control functions.
The most important POSIX functions are tcgetattr (3) and tcsetattr (3), which indicate obtaining and setting terminal properties respectively. You provide a pointer to the console structure that contains all available serial port options:
Table 3-console structure member
Member description
C_cflag Control Option
C_lflag current options
C_iflag input Option
C_oflag output options
C_cc control characters
C_ispeed input baud rate (New Interface)
C_ospeed output baud rate (New Interface)
Control Options
The c_cflag member controls the baud rate, some data bit, parity, stop bit, and hardware control flow. There are constants for all supported configurations.
Table 4-c_cflag member constant description
Constant description
Cbaud bit mask for baud rate
B0 0 BAUD (drop DTR)
B50 50 BAUD
B75 75 BAUD
B110 110 baud
B134 134.5 baud
B150 150 baud
B200200 baud
B300300 baud
B600 600 baud
B1200 1200 baud
B1800 1800 baud
B2400 2400 baud
B4800 4800 baud
B9600 9600 baud
B19200 19200 baud
B38400 38400 baud
B57600 57,600 baud
B76800 76,800 baud
B115200 115,200 baud
Exta external rate clock
Extb external rate clock
Csize bit mask for data bits
Cs5 5 data bits
CS6 6 data bits
Cs7 7 data bits
Cs8 8 data bits
Cstopb 2 Stop bits (1 otherwise)
Cread enable aggreger
Parenb enable parity bit
Parodd use odd parity instead of even
Hupcl hangup (drop DTR) on last close
Clocal local line-do not change "owner" of Port
Loblk block job control output
Cnew _ rtscts
Crtscts enable hardware Flow Control (not supported on all platforms)
The c_cflag member contains two options that should be applied frequently. clocal and cread. This will ensure that your program is not disturbed by other port control and suspension signals, and the serial port interface driver will read the incoming data.
The baud rate constant (cbaud, b9600, etc.) is used for older interfaces. They do not have c_ispeed or c_ospeed members. Refer to the POSIX function information in the next section to set the baud rate.
C_cflag (or other flag) members are not directly initialized. You should often use bitwise AND, Or, non-operations to set or clear Member spaces. Different Operating System versions (and even patches) have different applications. Therefore, bitwise operations will prevent you from using incorrect bitwise marks. These bitwise marks need to be updated with a serial drive.
Set the baud rate
The baud rates of different operating systems are stored in different places. The old interfaces rely on the baud rate constant in table 4 to store the c_cflag members. However, the updated applications provide c_ispeed and c_ospeed members who contain actual baud rate values.
Cfsetospeed (3) and cfsetispeed (3) functions provide the baud rate set to the console regardless of the operating system interface. Typically, you 'd better apply the following code to set the baud rate:
Listing 2-set the baud rate
Struct termios options;
/*
* Get the current port option ......
*/
Tcgetattr (FD, & options );
/*
* Set the baud rate to 19200 ....
*/
Cfsetispeed (& options, b19200 );
Cfsetospeed (& options, b19200 );
/*
* Start the receiver and set the local mode ......
*/
Options. c_cflag | = (clocal | cread );
/*
* Set new port options .......
*/
Tcsetattr (FD, tcsanow, & options );
The tcgetattr (3) function is filled with the serial port configurations you provide to the console. Then we set the baud rate and let the local mode run and the serial port receive data. We use tcsetattr (3). Select the new configuration. The tcsanow constant specifies that the changes should be executed immediately without waiting for the end of data transmission and receipt. There are other constants waiting for the input and output to complete or refresh the input and output cache.
Most systems do not support different input/output rates, so you must set the same value to ensure maximum portability.
Table 5-constants for tcsetattr
Constant description
Tcsanow make changes now without waiting for data to complete
Tcsadrain wait until everything has been transmitted
Tcsaflush flush input and output buffers and make the change
Set character size
Unlike the baud rate, there is no convenient function to set the character size. You must set a small bit mask. The character size is specified in the position:
Options. c_cflag & = ~ Csize;/* bit mask of character size */
Options. c_cflag | = cs8;/* select an 8-Bit Data bit */
Set parity
Like the character size you must manually set the parity enable and parity type bits. UNIX serial drivers support even, odd, and no parity bit generation. Space parity can be simulated with Clever coding.
You must manually set the parity enable and type like the byte size. UNIX serial drivers support odd, even, and non-parity series. Empty verification can be simulated using code.
No verification (8n1 ):
Options. c_cflag & = ~ Parenb
Options. c_cflag & = ~ Cstopb
Options. c_cflag & = ~ Csize;
Options. c_cflag | = cs8;
Odd check (7e1 ):
Options. c_cflag | = parenb
Options. c_cflag & = ~ Parodd
Options. c_cflag & = ~ Cstopb
Options. c_cflag & = ~ Csize;
Options. c_cflag | = cs7;
Even verification (7o1 ):
Options. c_cflag | = parenb
Options. c_cflag | = parodd
Options. c_cflag & = ~ Cstopb
Options. c_cflag & = ~ Csize;
Options. c_cflag | = cs7;
The null verification settings are the same as those without verification (7s1 ):
Options. c_cflag & = ~ Parenb
Options. c_cflag & = ~ Cstopb
Options. c_cflag & = ~ Csize;
Options. c_cflag | = cs8;
Set hardware Traffic Control
Some versions of UNIX Support Hardware throttling using the CTS and RTS signal lines. If the cnew_rtscts or crtscts constant is defined by the system, then the hardware traffic control can be supported. Follow the steps below to enable hardware throttling:
Options. c_cflag | = cnew_rtscts;/* also called crtscts */
Similarly, stop hardware traffic control l:
Options. c_cflag & = ~ Cnew_rtscts;
Local options
The local option Member c -- cflag controls how to input characters in the serial drive management. Generally, you can configure c_lflag members for standard or original input.