Preliminary exploration of serial port configuration under Linux


First, inStructure termsBasic configuration of serial port (such asBaud rate setting, check bit and stop bit setting And so on.


struct termios   //The setting of serial port is mainly settingMembers of struct termios
 tcflag_t  c_iflag;  //input mode flags  Enter the mode flag.
 tcflag_t  c_oflag;  //output mode flags  Output mode flag
 tcflag_t  c_cflag;  //control mode flags  Control mode flag
 tcflag_t  c_lflag;  //local mode flags  Local mode flag.

cc_t c_line;     //line discipline  Line regulation (rate).
 cc_t      c_cc[NCCS]; //control characterControl character array

1C cflag represents control mode

CLocal means to ignore the status lines of all modems. This is to ensure that the program does not occupy the serial port. Cread stands for enabling the character receiver to read the number of inputs from the serial portAccording to.

CS5/6/7/8Used to indicate sending or receiving characters5/6/7/8Bit.

CSTOPBIndicates that each character uses two stop bits.

HUPCLMeans to hang up the modem when shutting down.

PARENB:Enable parity code generation and detection.

PARODDOnly odd check is used instead of even check.

2c_iflagRepresents the input mode.

BRKINT:When one to one termination state is detected in the input line,An interrupt is generated.

TGNBRK:Ignore the termination status in the input line.

TCRNL:Converts the received carriage return to a new line character.

TGNCR:Ignore new line characters received.

INLCR:Converts the received new line character to a carriage return character.

IGNPAR:Ignore characters with parity errors.

INPCK:Perform parity check on received characters.

PARMRK:Mark parity errors.

ISTRIP:Reduce all received characters to7Bit.

IXOFF:Enable software flow control for input.

IXON:Enable software flow control on the output.

3c_ccSpecial control characters.

Standard mode and non-standard mode,c_ccArray subscripts have different values:

1)Standard mode:









(2)non-standard model:








Two):Among them,Through rightc_cflagAssignment can set baud rate, character size, data bit, stop bit, parity bit, hardware flow control, etc.

Procedures such as:

Structure terms options; / / serial port configuration structure
Tcgetattr (FD, & Options); / / get the current settings
Options. C | CFG | = b115200 | local | cread; / / set baud rate, local connection, receive enable
Options. C_cfg & = ~ CSize; / / mask data bits
Options. C | = CS8; / / data bit is 8, CS7 for 7
Options. C_cflag & = ~ cstop B; / / one stop bit, two stop bits = cstop B
Options. C_cflag & = ~ parentb; / / no verification
/ / options. C_cflag | = parentb; / / with verification
//Options. C_cflag & = ~ parodd / / parity
//Options. C | = parity / / parity

Options. C_cc [vtime] = 0; / / waiting time, in 100ms


Fail to meet the conditions or readThe remaining data in the buffer will be0Read after 100 milliseconds. Also pay special attention when settingAfter vtime, if the third parameter of read is less than Vmin, Vmin will be changed to the third parameter of read, that is, read (FD, & buf, m); will be used tolowerThe setting changes to:options.c_cc[VMIN] = m;

Options. C_cc [Vmin] = 0; / / minimum bytes


1Vmin = 0, when the number of buffer bytes is > = 0, the read operation is performed. In fact, the read serial port operation is not blocked at this time, because the condition is always met.

2Vmin = 1, when the number of buffer bytes is > = 1, the read operation is performed, and when there is no data, the read serial port operation is blocked.

3Vmin = 4, when the number of buffer bytes is > = 4, the read operation is performed, otherwise the read serial port operation is blocked. The maximum number of bytes per read is determined by the third parameter in the read function. Until the remaining data in the buffer is < read the third parameter and < 4 (if read the third parameter is 1 at this time, read 4 times until the buffer has been read. If read the third parameter is 2, read continuously until the buffer is empty or there is one character left).

4No settingsVtime, the rest of the characters have no fixed period of time until the next time the reading conditions are met.

tcflush(fd, TCIOFLUSH);

//Tciflush flushes the input queue.
The output queue will be flushed by / tcoflush.  
The input and output queues are flushed by ﹖ I ﹖ I ﹖ I ﹖ I ﹖ o ﹖ I / O
tcsetattr(fd, TCSANOW, &options);

//Tcsanow takes effect immediately;
                                    //TCSADRAIN:Wait until everything has been transmitted;
                                  //TCSAFLUSH:Flush input and output buffers and make the change

Above mentioned,When setting the baud rate, you need to add before the number‘B’。 Procedure example:


Two.Operate the serial port.Serial port is a terminal device

(1)The operation command is as follows:

Open serial port:fd = open( “/dev/ttyS0”, O_RDWR|O_NOCTTY|O_NDELAY);

O? Rdwr read / write mode is on;
O ﹣ noctty does not allow the process to manage the serial port;noticeLinix system, this program will not be the control of this portTerminal system.
O’ndelay non blocking (the default is blocking, and you can use fcntl() to reset after opening)noticeLinux The system doesn’t careThe state of the DCD signal line (whether the other end of the port is active or stopped).

Write inSerial portn = write(fd, “linux”, 5);
Number of bytes actually written;

readSerial portres = read(fd,buf,len);
Number of bytes read by

Set upSerial portFcntl (FD, f_setfl, fndelay); / / non blocking
Fcntl (FD, f-setfl, 0); / / blocking

CloseSerial portclose(fd);

(two)On the whole:

1. ThefunctionFunctions to be implemented in open port():

Procedures such as:

(1) open (“/ dev / ttys0”, O | rdwr | o | nocty | o | NDELAY); / * open serial port 0*/
(2) fcntl (FD, f ﹣ setfl, 0) / * restore the serial port to blocking state*/
(3) isatty (stdin ﹣ fileno) / * test whether the interrupt device is not 0, that is, the interrupt device.*/

2Configure serial port parameter functionFunctions to be implemented in set ﹐ opt():
(1) save the original serial port configuration

(2) clear the new serial port configuration

(3) the activation options CLocal and cread are used for local connection and reception.

newtio.c_cflag |=CLOCAL | CREAD;

(4) and set the data bit sizeMask setting required
newtio.c_cflag &= ~CSIZE;
newtio.c_cflag |=CS8;

(5) set parity
Odd parity check:
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
Parity check:
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PAREND;
newtio.c_cflag &= ~PARODD;
No parity:
newtio.c_cflag &= ~PARENB;

(6) set stop bitBy activatingThe implementation of cstop B in C ﹤ cflag. If stop bit is 1, cstop B will be cleared, if stop bit is 2, cstop B will be activated.
Newtio. C_cflag & = ~ cstop B; / * stop bit is 1*/
Newtio. C_cflag | = cstop B; / * stop bit is 0*/

(7) set baud rate:

(8) set waiting time and minimum acceptance charactersIf there is no special requirement for receiving characters and waiting time, it can be set to0:
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;

(9) process as received characterHandleReference object to write)。The tcflush function flushes (discards) the input cache (received by the terminal driver but not yet read by the user program) or the output cache (written but not yet sent by the user program).

//Tciflush clear input queueNamelyRefresh received data but do not read

Clear output queueNamelyRefresh written data but do not transfer

Clear input and output queuesNamelyRefresh received data but not read at the same time, and refresh the number of writesAccording to but not transmitted.

(10) activate new configuration:
3Read write serial port

(three)In addition:

1、Get file’sFlags, the second parameter of the open function:

       flags = fcntl(fd,F_GETFL,0);

2. Set the flags of the file:


3. Add a flag of the file. For example, if the file is blocked, you want to set it as non blocking:

       flags = fcntl(fd,F_GETFL,0);

       flags |= O_NONBLOCK;


4. Cancel a flag of the file. For example, if the file is non blocking, you want to set it as blocking:

      flags = fcntl(fd,F_GETFL,0);

      flags &= ~O_NONBLOCK;