LINUX serial port application development

Source: Internet
Author: User
Tags control characters vmin

LINUX serial port application development
Serial Port Overview
There are two basic data communication methods:
Parallel Communication;
Serial Communication
Serial Communication is a commonly used computer interface, such as RS-232-C interface. This standard requires a db25-core pin connector or a DB9-core pin connector. The chip usually has UART Controller, which can work in interrupt (interrupt mode) or

DMA (Direct Memory Access) mode.
UART operations mainly include the following parts:
Data transmission;
Receive data;
Interrupt;
Generate a baud rate;
Loopback mode;
Infrared mode;
Automatic traffic control mode;
The configuration of serial port parameters mainly includes: baud rate, data bit, stop bit, and traffic control protocol.

In Linux, the serial port device files are stored in the/dev directory. The names of Serial Port 1 and Serial Port 2 are sequential: "/dev/ttys0" and "/dev/ttys1 ".
In Linux, the serial port is the same as the operating file.

Serial Port Configuration
Before using the serial port, you must configure the configuration, including the baud rate, data bit, check bit, and stop bit. Serial port settings are implemented by the following struct:
Struct termios {
Tcflag_t c_iflag;/* input flage */
Tcflag_t c_oflag;/* output flags */
Tcflag_t c_cflag;/* control flags */
Tcflag_t c_lflag;/* local flags */
Cc_t c_cc [NCCs];/* control characters */
};
In this structure, c_cflag is the most important. You can set the baud rate, data bit, check bit, and stop bit. When setting the baud rate, add 'B' before the number, such as b9600 and b19200. To use it, you must use the "and" or "operation method.
C_cflag CTS s_oflow output CTS Flow Control
Cignore ignore control flag
Clocal ignores the status line of the decimal-modem.
Enable the receiving device in cread
Crts_iflow input RTS Stream Control
Csize character size screen
Cstopb sends two stop bits; otherwise, the value is 1.
Disconnected When hupcl is closed at last
Mdmbuf throttling output by Carrier
Parenb performs parity check by default.
Parodd odd school, otherwise it is an even school
Input mode c_iflag members control the character input at the receiving end of the port.
C_iflag brkint generates SIGINT when it is connected to break
Icrnl converts the input Cr to Nl
Ignbrk ignores the break Condition
Igncr ignore cr
Ignpar ignores parity error characters
Imaxbel ring in the input queue Space
Inlcr converts the input NL to Cr
Inpck enable input parity
Istrip detaches 8th characters from the input
Iuclc converts the input uppercase/lowercase characters
Ixany enables output to be restarted for any character
Ixoff enable/Stop input control flow
Ixon enables start/stop output control flow to take effect
Parmrk mark parity error
Serial control functions
Tcgetattr properties (termios structure)
Tcsetattr setting attributes (termios structure)
Cfgetispeed
Cfgetospeed: output speed
Cfsetispeed
Cfsetospeed: Set the output speed
Tcdrain waiting for all output to be transmitted
Tcflow suspends transmission or receiving
Tcflush clears pending Input and Output
Tcsendbreak send break characters
Tcgetpgrp get the front-end process group ID
Tcsetpgrp

Serial port configuration process
(1) Save the original serial port configuration and use the tcgetattr (FD, & oldtio) Function
Struct termios newtio, oldtio; tcgetattr (FD, & oldtio );
(2) activation options include clocal and cread for local connection and reception. Newtio. c_cflag | = clocal | cread;
(3) set the baud rate and use the cfsetispeed and cfsetospeed functions.
Cfsetispeed (& newtio, b115200 );
Cfsetospeed (& newtio, b115200 );
(4) use a mask to set the data bit.
Newtio. c_cflag & = ~ Csize;
Newtio. c_cflag | = cs8;
(5) set the parity bit and use c_cflag and c_iflag.
Set odd check:
Newtio. c_cflag | = parenb;
Newtio. c_cflag | = parodd;
Newtio. c_iflag | = (inpck | istrip );
Configure even Verification:
Newtio. c_iflag | = (inpck | istrip );
Newtio. c_cflag | = parenb;
Newtio. c_cflag & = ~ Parodd;
(5) set the stop bit to activate cstopb in c_cflag. If the stop bit is 1, clear cstopb. If the stop bit is 2, activate cstopb.
Newtio. c_cflag & = ~ Cstopb;
(6) set the minimum character and wait time. If there is no special requirement on the receiving character and wait time, it can be set to 0.
Newtio. c_cc [vtime] = 0;
Newtio. c_cc [Vmin] = 0;
(7) process the reference object to be written. The tcflush function clears (discards) the input cache (the Terminal Driver has received it, but the user program has not read it) or the output cache (the user program has already written it, but not yet sent ).
Int tcflush (INT filedes, int Queue)
The number of queue must be one of the following three constants:
Tciflush clear input queue
Tcoflush clears the output queue.
Tcioflush clears input and output queues.
For example, tcflush (FD, tciflush );
(8) activate the configuration. After the configuration is complete, you need to activate the configuration to make it take effect. Use

Tsettattr () function. Prototype:
Int tcgetattr (INT filedes, struct termios * termptr );
Int tcsetattr (INT filedes, int opt, const struct termios

* Termptr );
The opt parameter of tcsetattr allows us to specify when new terminal properties will take effect. Opt can be specified as one of the following constants:
Tcsanow changes occur immediately.
Tcsadrain sends all the output before the change occurs. If you change the output parameter, use this option.
Tcsaflush sends all the output before the change occurs. Furthermore, when column modification occurs, all input data that has not been read is deleted (flushed) for use such as tcsetattr (FD, tcsanow, & newtio)

 

Serial Port usage details
After configuring the relevant properties of the serial port, you can open and read/write the serial port. It is used in the same way as file operations. The difference is that the serial port is a terminal device.
Open serial port
FD = open ("/dev/ttys0", o_rdwr | o_noctty | o_ndelay );
In the open function, except for common parameters, there are two other parameters: o_noctty and o_ndelay.
O_noctty: notifies the Linux system that this program will not be the control terminal for this port.
O_ndelay: notifies the Linux system not to care about the status of the DCD signal line (whether the other end of the port is activated or stopped ).
Then, the serial port is restored to the blocking status, which is used to wait for the serial data to be read. Use the fcntl function:
Fcntl (FD, f_setfl, 0 );
Then, test whether the opened file descriptor references a terminal device to further confirm whether the serial port is opened correctly.
Isatty (stdin_fileno );

 

Read/write serial port
The Read and Write Functions of the serial port are the same as those of common files.
Read (FD, buff, 8 );
Write (FD, buff, 8 );
For more information, see Seri. C.
# Include <stdio. h>
# Include <string. h>
# Include <sys/types. h>
# Include <errno. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <termios. h>
# Include <stdlib. h>

Int set_opt (int fd, int nspeed, int nbits, char nevent, int

Nstop ){
/* FD sets the descriptor of the graph File
Nspeed baud rate
Nbits data bit
Nevent Verification
Nstop stop bit
*/
Struct termios newtio, oldtio;
If (togetattr (FD, & oldtio )! = 0 ){
Perror ("setupserial 1 ");
Return-1;
}
Bzero (& newtio, sizeof (newtio ));
Newtio. c_cflag | = clocal | cread;
Newtio. c_cflag & = ~ Csize;
Switch (nbits ){
Case 7:
Newtio. c_cflag | = cs7;
Break;
Case 8:
Newtio. c_cflag | = cs8;
Break;
}
Switch (nevent ){
Case 'O ':
Newtio. c_cflag | = parenb;
Newtio. c_cflag | = parodd;
Newtio. c_iflag | = (inpck | istrip );
Break;
Case 'E ':
Newtio. c_iflag | = (inpck | istrip );
Newtio. c_cflag | = parenb;
Newtio. c_cflag & = ~ Parodd;
Break;
Case 'N ':
Newtio. c_cflag & = ~ Parenb;
Break;
}

Switch (nspeed ){
Case 2400:
Cfsetispeed (& newtio, b2400 );
Cfsetospeed (& newtio, b2400 );
Break;
Case 4800:
Cfsetispeed (& newtio, b4800 );
Cfsetospeed (& newtio, b4800 );
Break;
Case 9600:
Cfsetispeed (& newtio, b9600 );
Cfsetospeed (& newtio, b9600 );
Break;
Case 1152000:
Cfsetispeed (& newtio, b115200 );
Cfsetospeed (& newtio, b115200 );
Break;
Default:
Cfsetispeed (& newtio, b9600 );
Cfsetospeed (& newtio, b9600 );
Break;
}

If (nstop = 1)
Newtio. c_cflag & = ~ Cstopb;
Else if (nstop = 2)
Newtio. c_cflag | = cstopb;

Newtio. c_cc [vtime] = 0;
Newtio. c_cc [Vmin] = 0;

Tcflush (FD, tciflush );

If (tcsetattr (FD, tcsanow, & newtio ))! = 0 ){
Perror ("Com set error ");
Return-1;
}
Print ("set done! /N ");
Return 0;
}

Int open_port (int fd, int comport ){
Char * Dev [] = {"/dev/ttys0", "/dev/ttys1", "/dev/ttys2 "}
Long vdisable;
If (comport = 1 ){
FD = open ("/dev/ttys0", o_rdwr | o_noctty | o_ndelay );
If (-1 = FD ){
Perror ("can't open serial port ");
Return (-1 );
}
Else printf ("Open ttys0..../N ");
}
If (comport = 2 ){
FD = open ("/dev/ttys1", o_rdwr | o_noctty | o_ndelay );
If (-1 = FD ){
Perror ("can't open serial port ");
Return (-1 );
}
Else printf ("Open ttys1....../N ");
}
If (comport = 3 ){
FD = open ("/dev/ttys2", o_rdwr | o_noctty | o_ndelay );
If (-1 = FD ){
Perror ("can't open serial port ");
Return (-1 );
}
Else printf ("Open ttys2..../N ");
}
If (fcntl (FD, f_setfl, 0) <0)
Printf ("fcntl failed! /N ");
Else
Printf ("fcntl = % d/N", fcntl (FD, f_setfl, 0 ));
If (isatty (stdin_fileno) = 0)
Printf ("standard input is not a terminal device/N ");
Else
Printf ("isaty success! /N ");
Printf ("FD-open = % d/N", FD );
Return FD;
}

Int main (void ){
Int FD;
Int nread, I;
Char buff [] = "Hello/N ";

If (FD = open_port (FD, 1) <0 ){
Perror ("open_port error ");
Return;
}
If (I = set_opt (FD, 115200,9, 'n', 1) <0 ){
Perror ("set_opt error ");
Return;
}

Printf ("FD = % d/N", FD );
Nread = read (FD, buff, 8 );
Printf ("nread = % d, % s/n", nread, buff );
Close (FD );
Return;
}

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.