Tcgetattr
function is used to obtain terminal-related parameters. Parameter FD is a terminal file descriptor, and the returned result is stored in the Termios structure.
Http://baike.baidu.com/view/5644808.htm?fr=aladdin
The TCSETATTR function is used to set the terminal's related parameters
Tcflush UNIX terminal I/O functions. Role: Empty terminal incomplete input/output requests and data for baud rate settings are usually done using the cfsetospeed and Cfsetispeed functions. The baud rate information is obtained through the cfgetispeed and Cfgetospeed functions.
Common Functions
Open the serial port using the open () function, which has two parameters, the first is the device name to open (for example,/DEV/TTYS0). The second one is the way to open it. There are three ways to open this:
O_rdwr, which means that the serial port is opened in read-write mode.
O_noctty, which means that the control terminal does not become a port, if this option is not available, any input (keyboard key) will interrupt the execution of the program.
O_ndelay, indicates that the program does not pay attention to the state of the DCD signal line, that is, whether the device is running or hanging. If this option is not available, the program is set to sleep until the DCD signal is low.
The successful opening of the serial port will return the file descriptor, and the Open failure returns-1. The following is an example of an open serial port:
FD = open ("/dev/ttys0", o_rdwr| o_ndelay| O_ndelay);
Use Close () to turn off the open serial port, the only parameter is the file descriptor that opens the serial port. The following is an example of shutting down a serial port:
Close (FD); FD is the file descriptor that is returned by opening the serial port
Writes the data to the serial port using the Write () function. The following is an example of writing data to a serial port:
n = Write (Fd,buff,len);
/* n Indicates the number of bytes successfully written to the serial port, and if write fails, return-1
FD is the file descriptor returned by opening the serial port
buff represents the length of written
information Len represents.
*/
Reads the data from the serial port using the Read () function. The following is an example of reading data from a serial port:
n = read (Fd,buff,len);
/* n Indicates the number of bytes read from the serial port
FD is the file descriptor
buff is the read bytes stored in the buffer
Len indicates the number of bytes read
* *
The Fcntl () function enables you to manipulate file descriptors to control the state of reading data. Fcntl (fd,f_setfl,0) means that no data is blocked, waits until data arrives, and Fcntl (Fd,f_setfl,fndelay) returns 0 as soon as the port has no data. set serial port Properties
All serial properties are in a struct named Termios that you want to use to include the Termios.h header file. The header file also defines two important functions tcgetattr () and tcsetattr (), respectively, to get and set the properties of the serial port. such as: Tcgetattr (Fd,&old_termios), tcsetattr (Fd,tcsanow,&new_termios). Old_termios is the old serial port property, New_termios is the new serial port property that is reset. The meaning of constants in the Tcsetattr () function is:
Tcsanow indicates that the new set of serial properties will take effect immediately.
Tcsadrain says all data transfer will not take effect until it is completed.
Tcsaflush says to empty the input and output caches immediately, and then apply the new serial port settings.
Termios Structure Body Content:
Member description
-------------------------------------------
c_cflag control mode flag
C_lflag local mode flag
C_ Iflag Input mode flag
C_oflag output mode flag
C_line line discipline
C_cc[nccs] control character
C_ Ispeed input baud rate
c_ospeed output baud rate
The four flags in the Termios structure control four different parts of the input output. The input pattern flag C_iflag determines how to interpret and process the received characters. The output mode flag C_oflag determines how to interpret and process characters sent to a TTY device. The control mode flag determines a series of protocol characteristics of a device, which is only valid for physical devices. The local mode flag C_lflag determines how characters are collected and processed before they are exported.
In the serial transmission, the baud rate to express the speed of transmission, 1 Baud said in 1 seconds can transmit 1 yards. The baud rate setting can be done using the Cfsetispeed (&new_termios,b19200) and Cfsetospeed (&new_termios,b19200) functions, with the default baud rate of 9600baud. The Cfsetispeed () function is used to set the baud rate of the input, and the Cfsetospeed () function is used to set the baud rate of the output. B19200 is a macro defined in the Termios.h header file that represents the baud rate of 19200.
Clocal and Cread is the C_cflag member of the rate-related signs, in the serial port programming, these two signs must be effective to ensure that the program in the sudden operation control or suspend, will not become the port of possession, while the receiver of the serial port will automatically read data. Set the method as follows:
Termios_new.c_cflag |= clocal; Guarantee program will not become the end of the possessor
termios_new.c_cflag |= cread; Enable the port to read the input data
Setting the serial port properties cannot be directly assigned, to be implemented by the "and" and "or" actions of different members of the Termios. In the Termios.h file, a variety of constants are defined, such as the clocal,cread described above. The values of these constants are masks, which enable the setting of serial properties by logically manipulating these constants with the Termios struct members. Use "|=" to enable properties while programming, and "&=~" to cancel the property.
C_iflag Input Logo Description
Brkint and IGNBRK
If IGNBRK is set, the interrupt condition is ignored. If the brkint is set without setting the IGNBRK, the interrupt condition empties all the data in the input output queue and sends a SIGINT signal to all processes in the TTY foreground process group. If neither is set, the break condition is treated as a 0 character. At this point, if the PARMRK is set, when a frame error is detected, the application is sent three bytes of ' \377 ', instead of sending only one '.
Parmrk and Ignpar
If Ignpar is set, the parity error or frame error of the received data is ignored (in addition to the interrupt condition mentioned earlier). If the PARMRK is set without setting the Ignpar, the received byte has a parity error or frame error. A three-byte ' \377 ' ' \ n ' ERROR report will be sent to the application. where n represents the bytes received. If neither is set, a single byte (' * ') report is sent to the application in addition to the bytes received with a parity error or an abort condition other than the frame error.
Inpck
If set, parity is performed. Without parity, PARMRK and Ignpar will have no effect on the existence of parity errors.
Istrip
If set, the high order of all bytes received will be removed to ensure that they are a 7-bit character.
Inlcr
If set, the incoming newline character (' \ n ') will be converted to a carriage return (' \ R ').
Igncr
If set, all received return characters (' \ R ') are ignored.
Icrnl
If set, but IGNCR is not set, the received carriage return will be converted to a newline character when it is sent to the application.
Iuclc
If both IUCLC and Iexten are set, all uppercase letters received are converted to lowercase letters when they are sent to the program. The tag is not defined in POSIX.
Ixoff
If set, to avoid an input buffer overflow for a TTY device, the TTY device can send a stop character ^s and a start ^q to the terminal, requiring the terminal to stop or restart sending data to the computer. The way to control data flow through stop and start is called software flow control, the software flow control mode is less, we mainly use hardware flow control mode. The hardware flow control is set in the C_cflag flag.
Ixon
If set, the ^s will stop outputting to the TTY device and the output will be restored after receiving the ^q.
Ixany
If set, any character will start the output again, not just ^q characters.
Imaxbel
If set, any character that is received when the input buffer space is full will emit an alert ' \a '. The tag is not defined in POSIX.
c_oflag Output Flag Description
Opost is a POSIX-defined only flag, and other non-POSIX output tags take effect only if the flag is set.
Opost
The tag is turned on, and subsequent output marks do not take effect. Otherwise, the output data is not processed.
Olcuc
If set, uppercase letters are converted to lowercase letters output.
Onlcr
If set, send a carriage return (' \ R ') before sending a line break (' \ n ').
Onocr
If set, when the current column is 0 o'clock, the carriage return is not sent and will not be processed.
Ocrnl
If set, the return character is converted to a newline character. Also, if Onlret is set, the current column is set to 0.
Onlret
If set, the current column is set to 0 when a newline character or carriage return is sent.
Oxtabs
If set, the tab character is converted to spaces. C_cflag control mode logo Description
Clocal
If set, the modem's control line will be ignored. If not set, the open () function blocks until the carrier detection line announces that the modem is in the picking state.
Cread
You must set the tag to receive characters only if you set it.
CSize
Sets the number of bits to transfer characters. CS5 represents 5 bits per character, CS6 represents 6 bits per character, CS7 represents 7 bits per character, and CS8 represents 8 bits per character.
Cstopb
Sets the number of digits for the stop bit, or, if set, generates two stop bits after each frame, or a stop bit if there is no setting. A stop bit is generally used. A device that requires a two-bit stop bit is obsolete.
Hupcl
If set, the DTR and RTS lines on the serial port will weaken the signal when the last file descriptor opened by the device is closed, informing the modem to hang up. In other words, when a user through the modem dial login system, and then log off, then the modem will automatically hang up.
Parenb and Parodd
If you set Parenb, a parity bit is generated. If Parodd is not set, a parity bit is generated, and if Parodd is set, a parity bit is generated. If Parenb is not set, the parodd settings are ignored.
Crtscts
Use hardware flow control. In high-speed (19200bps or higher) transmission, the use of software flow control will reduce the efficiency, this time must use hardware flow control.
c_cc[] Control character Description
POSIX does not have a defined control character to use in Linux only if Iexiten is set in the local mode flag C_lflag. Each control character corresponds to a key combination (^c, ^h, etc.), except for the two control characters, Vmin and Vtime, which do not correspond to the control character. These two control characters are valid only in the original mode.
C_CC[VINTR]
The default corresponding control character is ^c, which clears the input and output queue data and sends a SIGINT signal to each program in the foreground process group of the TTY device, and the process that does not define the handler for the SIGINT signal exits immediately.
C_cc[vquit]
The default corresponding control character is ^\, which clears the input and output queue data and sends a SIGQUIT signal to each program in the foreground process group of the TTY device, and the process that does not define the handler for the sigquit signal exits immediately.
C_cc[verase]
The default corresponding control character is ^h or ^, which, in standard mode, deletes the previous character, which has no effect in the original mode.
C_cc[vkill]
The default corresponding control is ^u, which, in standard mode, deletes the entire line of characters, which has no effect in the original mode.
C_cc[veof]
The default corresponding control character is ^d, in standard mode, using read () to return 0, marking the end of a file.
C_cc[vstop]
The default control character is ^s, which pauses the output with a TTY device until the Vstart control character is received. Alternatively, if the device is Ixany, the output will begin when any character is received.
C_cc[vstart]
The default corresponding control character is ^q, which is the function of restarting the output of the TTY device being paused.
C_CC[VSUSP]
The default corresponding control character is ^z, which causes the current foreground process to receive a SIGTSTP signal.
C_cc[veol] and C_cc[veol2]
In standard mode, these two subscript lines are preceded by a newline character (' \ n '), marking the end of a row, so that the data in the buffer is sent and a new row is started. VEOL2 is not defined in POSIX.
C_cc[vreprint]
The default corresponding control character is ^r, in standard mode, if the local mode flag echo is set, the corresponding control and newline characters are displayed locally, and the characters in the current buffer are printed again by using Verprint. Verprint is not defined in POSIX.
C_cc[vwerase]
The default corresponding control character is ^w, in standard mode, deletes all the spaces at the end of the buffer, and then deletes the non spaces adjacent to it, thereby removing the previous word from the line. Vwerase is not defined in POSIX.
C_cc[vlnext]
The default corresponding control character is ^v, which allows the next character to enter the buffer intact. If you want to allow ^v characters to enter the buffer, you need to press ^V twice. Vlnext is not defined in POSIX.
To disable a control character, simply set it to _posix_vdisable. However, this constant is only valid in Linux, so do not use this constant if your program is considering portability issues. C_lflag Local mode flag Description
Icanon
If set, the standard mode is started, and if there is no setting, the original mode is started.
ECHO
If set, The local echo is started. If not set, other tags that begin with echo will fail except for echonl.
Echoctl
If set, the control characters are printed in ^c, such as: Press CTRL + C to display ^c, press CTRL +. Show ^?.
Echoe
If the Echoe flag is set in standard mode, the previous display character is deleted when a erase control is received.
Echok and Echoke
In standard mode, when a Kill control character is received, the current row is deleted in the buffer. If Echok, Echoke, and Echoe are not set, the kill character (^u) represented in Echoctl will be displayed on the output terminal, indicating that the current row has been deleted.
If Echoe and Echok are already set, but Echoke is not set, the Kill character Echoctl represents is displayed at the output terminal, followed by a newline, and if Opost is set, the appropriate processing is done through the Opost handler.
If Echok, Echoke, and Echoe are set, the current row is deleted.
There is no echoke tag defined in POSIX, and in a system that does not have a echoke tag defined, setting Echok indicates that the ECHOKE flag is set at the same time.
Echonl
If the flag is set in standard mode, the line break will be displayed even if the ECHO flag is not set.
Echoprt
If set, the characters are simply printed, including various control characters. This flag is not defined in POSIX.
Isig
If set, the signals SIGINT, Sigquit, and sigtstp that correspond to Intr, quit, and Susp are sent to all processes in the foreground process group of the TTY device.
Noflsh
In general, the input output queue is emptied when the Intr or quit control is received, and the input queue is emptied when the Susp control character is received. However, if the Noflush flag is set, all queues will not be emptied.
Tostop
If set, the signal Sigttou is sent to the process group that the process is in when a process that is not a foreground process group attempts to write data to its control terminal. By default, this signal causes the process to stop, just as you receive the Susp control character.
Iexien
Default is set, we should not modify it. IUCLC and several tags associated with deletion characters in Linux require that Iexien be set to work properly.
here are some common methods for setting serial port properties.
Set flow control
Termios_new.c_cflag &= ~crtscts; Do not use flow control
termios_new.c_cflag |= crtscts; Using hardware flow control
Termios_new.c_iflag |= ixon| Ixoff| Ixany; Using Software flow control
Masked character size bit
Termios_new.c_cflag &= ~csize;
Set data bit size
Termios_new.c_cflag |= CS8; Use 8 bit data bits
termios_new.c_cflag |= CS7; Use 7 bit data bits
termios_new.c_cflag |= CS6; Use 6 bit data bits
termios_new.c_cflag |= CS5; Use 5-bit data bits
Set parity mode
Termios_new.c_cflag &= ~parenb; No parity check
termios_new.c_cflag |= parenb; Odd check
termios_new.c_cflag &= ~parodd;
Termios_new.c_cflag |= Parenb; Parity
Termios_new.c_cflag &= ~parodd;
Stop bit
Termios_new.c_cflag |= CSTOPB; 2-bit stop bit
termios_new.c_cflag &= ~CSTOPB; 1-bit stop bit
Output mode
Termios_new.c_cflag &= ~opost; Raw data (raw) output
Control characters
Termios_new.c_cc[vmin] = 1; Read the minimum number of characters
termios_new.c_cc[vtime] = 1; The wait time to read the first character
Turning off terminal Echo, the characters entered by the keyboard are not displayed in the terminal window.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h >
int main (void)
{
struct termios ts,ots;
Char passbuf[1024];
Tcgetattr (stdin_fileno,&ts); /* Stdin_fileno value is 1, representing the standard input file descriptor *
/ots = ts;
Ts.c_lflag &= ~echo; /* Close back to terminal echo function * *
ts.c_lflag |= echonl;
Tcsetattr (stdin_fileno,tcsaflush,&ts); /* Apply the new terminal set * *
fgets (Passbuf,1024,stdin); /* Input characters will not be displayed in the terminal
/printf ("you input character =%s\n", passbuf);
Tcsetattr (stdin_fileno,tcsanow,&ots); /* Restore the old terminal equipment */
}
serial port itself, standard and hardware †
The serial port is the physical interface of serial communication on the computer. In the history of computers, serial ports have been used extensively to connect computers and terminals and various external devices. Although Ethernet interfaces and USB interfaces are also transmitted as data via a serial stream, serial connections are usually referred specifically to those that are compatible with the RS-232 standard hardware or modem interface. Although now on many personal computers, the original used to connect the external devices of the serial port has been widely replaced by USB and FireWire, and the original connection to the network of the serial port is replaced by Ethernet, but also to connect the terminal serial device has been MDA or VGA replaced. However, on the one hand because the serial port itself cost cheap technology mature, on the other hand, because the serial port of the console function RS-232 standard highly standardized and very popular, so until now it is still widely used in various devices. Some computers use an integrated circuit called UART as a serial device. This integrated circuit can be used for conversion between characters and asynchronous serial communication sequences, and can automatically process data timing. And some low-end devices will allow the CPU directly through the output pin to transmit data, this technology is called bit-banging. Because the "serial port", RS-232 and UARTs basically always appear in the same context, so these nouns are often confused. Here are some important terms and phrases to explain below. ↑ What is serial communication †
A computer can transmit one or more bits of data at a time. "Serial" refers to a type that transmits only one bit (1bit) of data at a time. When you need to transmit a word (word) data through serial communication, you can only receive or send it in one bit at a time. Each bit may be on (1) or off (0). In many technical terms, mark is used to express on, while space denotes off.
The speed of serial data is usually expressed in bytes bits-per-second (bps) or baud rate (baud) transmitted per second. This value represents the number of 0 and 1 sent out per second. A long time ago, 300bps was fast, and now the computer can handle up to 430,800 RS-232 rate. The unit that represents the baud rate also has KPBS and mbps,1kps=1000bps and 1mbps=1000kbps. When a serial device is commonly referred to, it is usually said to be a data communication device (-DCE) (data Communications equipment), or the-dte of an information terminal (Terminal). The difference between them is very simple, each signal pair, such as transmission and reception, they are exactly the opposite. If you need to connect two DTE or DCE devices, you will need an adapter or crossover cable to swap the signals. ↑ What is rs-232†
RS-232 is the electrical interface for serial communications defined by EIA (Electronic Industries Association). RS-232 In fact there are three kinds (a,b and C), which use different voltages to represent on and off. The most widely used is rs-232c, which defines the voltage of the mark (on) bit as -3v to -12v, while the voltage of space (off) is defined between +3v and +12v. Although the RS-232C standard says the signal is transmitted at a distance of 8m, in fact you can use it to transmit longer distances until the signal baud rate is too small to die. The wire that is used to pass in outgoing data is removed from the RS-232 link, and there are wires that provide timing, state, and handshake:
RS-232 PIN Definition
DB-25
Stitch |
Describe |
Stitch |
Describe |
Stitch |
Describe |
Stitch |
Describe |
Stitch |
Describe |
1 |
Earth Ground |
6 |
Dsr-data Set Ready |
11 |
Unassigned |
16 |
Secondary RXD |
21st |
Signal Quality Detect |
2 |
Txd-transmitted Data |
7 |
Gnd-logic Ground |
12 |
Secondary DCD |
17 |
Receiver Clock |
22 |
Ring Detect |
3 |
Rxd-received Data |
8 |
Dcd-data Carrier Detecter |
13 |
Secondary CTS |
18 |
Unassigned |
23 |
Data Rate Select |
4 |
Rts-request to Send |
9 |
Reserved |
14 |
Secondary TXD |
19 |
Secondary RTS |