LINUX serial Programming analysis

Source: Internet
Author: User
Tags comparison table unsupported
You may not be familiar with this topic any more. There are a lot of online materials, because this is an important aspect of programming in Linux, and there are many people who understand this aspect; here I just want to give a brief introduction to this knowledge for beginners:
To put it bluntly, serial programming connects the computer to the machine to be controlled with a serial port, and then sends specified data or controls to the lower computer through programming, or transmission, and then receive the information from the lower computer to indicate whether it is correct. Is it vulgar!
Serial Port is a protocol for communication between very common devices on computers. Commonly Used PCs contain RS232 serial ports. Of course, in addition to RS232, there are also RS485 and rs422 specifications, it is used for communication between different devices. The RS232 serial port programming is introduced here.
In serial programming, it is important to set the serial port. The configuration includes the baud rate, data bit, stop bit, and parity bit, the default settings for the serial port of each machine may be different. If you do not set these settings, send data only according to the default settings, it is very likely that n many different ideas cannot be found; therefore, before real communication, we must set these:
The following describes the functions of these basic settings (in fact, they are all fixed frameworks, Program )~ O ~
1. Set the baud rate
Note that each machine has a speed of output and input acceptance information, so cfsetispeed and cfsetospeed are used to set them separately. Note that a structure such as struct termios includes all settings on the serial port, it is also used below. It is defined in termios. h .. It is hard to understand why speed_arr and name_arr arrays are set. This is because in linuxe, the system has specially prepared a table with b38400 and b19200 ...... instead, we can only pass in the and values. Therefore, we can compare the values we passed in with name_arr. If they are the same, we can retrieve the corresponding values from the system comparison table and set them, if the parameter value does not exist in the system comparison table, the parameter is not set.
Int speed_arr [] = {b38400, b19200, b9600, b4800, b2400, b1200, b300 ,//
B38400, b19200, b9600, b4800, b2400, b1200, b300 ,};
Int name_arr [] = {38400,192 00, 9600,480 0, 2400,120 0, 300,
38400,192 00, 9600,480 0, 2400,120 0, 300 ,};
Void set_speed (int fd, int speed)
{
Nt I;
Int status;
Struct termios OPT; // defines such a structure
Tcgetattr (FD, & OPT); // used to obtain the default settings of the machine's original Port
For (I = 0; I judge whether the input is equal
{
Tcflush (FD, tcioflush); // refresh the input/output buffer
Cfsetispeed (& OPT, speed_arr); // set
Cfsetospeed (& OPT, speed_arr );
Status = tcsetattr (FD, tcsanow, & OPT); // This is to immediately write the bote rates settings to the serial port
If (status! = 0)
Perror ("tcsetattr fd1"); // The setting is incorrect.
Return;
}
Tcflush (FD, tcioflush); // same as above
}
}
2. Set parity, data, and stop bit
These three parameters are usually set together. databits is the data bit, stopbits is the stop bit, and parity is the check bit.
These settings on the serial port are complex and complex. The termios Members define the c_cflag Control item c_lflag line item c_iflag input item c_oflag output item c_cc control character c_ispeed input Porter c_ospeed output Porter so many times, there are a lot of settings for each item. Here we don't talk about it as complicated. We will explain it with a general serial port framework, mainly for Parity, data, and stop bit settings. Other control items are introduced in the program:
Int set_parity (int fd, int databits, int stopbits, int parity)
{
Struct termios options; // define a structure
If (tcgetattr (FD, & options )! = 0) // first, read the system's default options. required.
{
Perror ("setupserial 1 ");
Return (false );
}
Options. c_cflag & = ~ Csize; // This is to set the c_cflag option not to use the bitwise data mask.
Switch (databits)/* set the number of data digits */
{
Case 7:
Options. c_cflag | = cs7; // set the c_cflag option data bit to 7 bits
Break;
Case 8:
Options. c_cflag | = cs8; // sets the data bit of the c_cflag option to 8 bits.
Break;
Default:
Fprintf (stderr, "unsupported data size \ n"); // none of the above
Return (false );
}
/*
Parenb enable parity generation on output and parity checking for input.
Inpck enable input parity checking.
Csize character size mask. Values are cs5, CS6, cs7, or cs8.
# Define csize 0000060
# Define cs5 5 0000000
# Define cs6. 0000020
# Define cs7 0000040.
# Define cs8. 0000060
Parodd if set, then parity for input and output is odd; otherwise even parity is used.
*/
Switch (parity) // sets the parity. The values of c_cflag and c_iflag are valid.
{
Case 'N ':
Case 'N': // Of course, this parameter is not selected if no verification is performed.
Options. c_cflag & = ~ Parenb;/* clear parity enable */
Options. c_iflag & = ~ Inpck;/* enable parity checking */
Break;
Case 'O': // The parenb check bit is valid.
Inpck check and Verification
Case 'O': Options. c_cflag | = (parodd | parenb);/* set it to an odd effect */
Options. c_iflag | = inpck;/* disnable parity checking */
Break;
Case 'E ':
Case 'E': // even check. If the odd check is not selected, the even check is performed.
Options. c_cflag | = parenb;/* enable parity */
Options. c_cflag & = ~ Parodd;/* convert to an even test */
Options. c_iflag | = inpck;/* disnable parity checking */inpck enable input parity checking.
Break;
Default:
Fprintf (stderr, "unsupported parity \ n ");
Return (false );
}
/* Set the stop bit */
Switch (stopbits) // This is the number of Stop bits, which indicates c_cflag
{
Case 1:
Options. c_cflag & = ~ Cstopb; // indicates a stop bit.
Break;
Case 2:
Options. c_cflag | = cstopb; // specify cstopb to indicate two. There are only two possibilities.
Break;
Default:
Fprintf (stderr, "unsupported Stop bits \ n ");
Return (false );
}
/* Set input parity option */
If (parity! = 'N') // specifies whether the input is verified.
Options. c_iflag | = inpck;
// This field is used to set the control characters and timeout parameters. Generally, the default value is enough. Note that the vstart and vstop elements of the c_cc array are set to DC1 and DC3, representing the ASCII standard Xon and xoff characters. Therefore, if these two characters cannot be transmitted, You need to block the software flow control. Options. c_iflag & = ~ (Ixon | ixoff | ixany );
Options. c_cc [vtime] = 150; // 15 seconds
Options. c_cc [Vmin] = 0;
Tcflush (FD, tciflush);/* update the options and do it now * // refresh and write it
If (tcsetattr (FD, tcsanow, & options )! = 0)
{
Perror ("setupserial 3 ");
Return (false );
}
Return (true );
}
// The serial port setting framework ends here. Most information can be transmitted for ports with the data bit check bit stop bit and the baud rate. In practice, there are often many special cases, such,
If you do not enter a carriage return when using write to send data, the message cannot be sent because the carriage return or line feed is accepted in the standard mode, in many cases, we do not need to press ENTER or line feed. In this case, we should switch to the line input mode and set options. c_lflag & = ~ (Icanon | echo | echoe | isig); directly sent without processing.
For example
When we send the character 0x0d, it is often the receiving side to get the character 0x0a this is what's going on, because in the serial port settings c_iflag and c_oflag There Is A ing from the NL-CR and CR-NL, that is, the serial port can regard carriage return and line feed as one character. Therefore, we should block these characters and use options. c_oflag & = ~ (Inlcr | igncr | icrnl |); and options. c_oflag & = ~ (Onlcr | ocrnl.
In short, the serial port settings are complicated and troublesome. You need to analyze the specific situation and find the corresponding method. If you find that the data cannot be transmitted, try to find the answer on the serial port settings.
Let's get down to the truth, and the next thing is very simple. Next we will open the serial port:
Int opendev (char * Dev)
{
Int FD = open (Dev, o_rdwr); // | o_noctty | o_ndelay
If (-1 = FD)
{/* Set the number of data digits */
Perror ("can't open serial port ");
Return-1;
}
Else
Return FD;
}
Then, the data is accepted and sent. It is easy to paste the General main function.
Int main (INT argc, char ** argv)
{
Int FD;
Int nread;
Char buff [512];
Char * Dev = "/dev/ttys0"; // The port in Linux is operated by opening the Device File
FD = opendev (Dev); // open
If (FD> 0)
Set_speed (FD, 19200); // set the baud rate 19200 after enabling
Else
{
Printf ("can't open serial port! \ N ");
Exit (0 );
}
If (set_parity (FD, 'n') = false) // set 8, 1, N. Note that communication can only be performed if it matches the preceding information with the lower computer.
{
Printf ("set parity error \ n ");
Exit (1 );
}
// Generally, read is used for reading, and write is used for writing. Read should be blocked before the program stops. Therefore, select should be used for control. Note that TV should be set for each loop; write does not need to consider blocking, but it must be written in the circular write mode. In fact, it is best to use the circular read mode to ensure that everything can be read and spliced together, and then other operations are being performed. At last, while (1) is a commonly used loop in serial communication, which is always executed until break is reached. These things are cumbersome, but they are actually nothing. This is not detailed here. The following is the simplest one ..
While (1)
{
While (nread = read (FD, buff, 512)> 0)
{
Printf ("\ nlen % d \ n", nread );
Buff [nread + 1] = '\ 0 ';
Printf ("\ n % s", buff );
}
}
// Close (FD );
// Exit (0 );
}
It's not difficult. In fact, apart from the new knowledge of serial port settings, Linux is actually a file, and the serial port is a device file. After the settings are complete, other things will be treated as files.

 

 Original article addressHttp://losemyheaven.blog.163.com/blog/static/1707198092010918104254996/

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.