Getting started with serial programming in Linux

Source: Internet
Author: User
Tags unsupported
Introduction to serial programming in Linux-general Linux technology-Linux programming and kernel information. For more information, see below. Introduction:

The Linux operating system has provided good support for the serial port from the very beginning. This article briefly introduces the serial port communication programming in Linux.

Introduction to serial ports

The serial port is a common interface for computers. It has a wide range of applications, such as a few connection lines and simple communication. Commonly used serial port is RS-232-C interface (also known as EIA RS-232-C) it was in 1970 by the American Association of Electronic Industry (EIA) the serial communication standard jointly developed by Bell systems, modem manufacturers, and computer terminal manufacturers. Its full name is "Technical Standard for Serial Binary data exchange interfaces between data terminal devices (DTE) and data communication devices (DCE)", which requires a 25-pin DB25 connector, specify the signal content of each pin of the connector and the signal levels. The transmission distance should be 4% in length when the code element distortion is less than 50 feet.

The Linux operating system has provided good support for the serial port from the very beginning. This article briefly introduces the serial port communication programming in Linux, it is recommended that you refer to Serial Programming Guide for POSIX Operating Systems.

Serial Port operation

Header files required for serial port operations

# Include /* Standard input/output definition */
# Include /* Standard function library definition */
# Include /* Unix standard function definition */
# Include
# Include
# Include /* File control definition */
# Include /* PPSIX terminal control definition */
# Include /* Error Code definition */



Open serial port

In Linux, the serial port file is located under/dev. Serial Port 1 is/dev/ttyS0, and serial port 2 is/dev/ttyS1. To open a serial port, use the standard file to open the function:

Int fd;
/* Open the serial port in read/write mode */
Fd = open ("/dev/ttyS0", O_RDWR );
If (-1 = fd ){
/* Unable to enable Serial Port 1 */
Perror ("error prompt! ");
}



Set serial port

The most basic settings for the serial port include the baud rate settings, the verification bit, and the stop bit settings. The serial port setting mainly sets the Member values of the struct termios struct.

Struct termio
{Unsigned short c_iflag;/* input mode flag */
Unsigned short c_oflag;/* output mode flag */
Unsigned short c_cflag;/* Control Mode flag */
Unsigned short c_lflag;/* local mode flags */
Unsigned char c_line;/* line discipline */
Unsigned char c_cc [NCC];/* control characters */
};



Setting this struct is complex. Here I will only talk about some common settings:

The following code modifies the baud rate:

Struct termios Opt;
Tcgetattr (fd, & Opt );
Cfsetispeed (& Opt, B19200);/* set it to 19200Bps */
Cfsetospeed (& Opt, B19200 );
Tcsetattr (fd, TCANOW, & Opt );



Example function for setting the baud rate:

/**
* @ Brief sets the serial communication rate
* @ Param fd type int refers to the file handle for opening the serial port
* @ Param speed Type int serial port speed
* @ Return void
*/
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,384 00,
19200,960 0, 4800,240 0, 1200,300 ,};
Void set_speed (int fd, int speed ){
Int I;
Int status;
Struct termios Opt;
Tcgetattr (fd, & Opt );
For (I = 0; I <sizeof (speed_arr)/sizeof (int); I ++ ){
If (speed = name_arr ){
Tcflush (fd, TCIOFLUSH );
Cfsetispeed (& Opt, speed_arr);
Cfsetospeed (& Opt, speed_arr);
Status = tcsetattr (fd1, TCSANOW, & Opt );
If (status! = 0 ){
Perror ("tcsetattr fd1 ");
Return;
}
Tcflush (fd, TCIOFLUSH );
}
}
}



Set the verification function:

/**
* @ Brief set the serial data bit, stop bit and verify bit
* @ Param fd type int indicates the serial port file handle opened
* @ Param databits type int data bit value: 7 or 8
* @ Param stopbits type int stop bit value: 1 or 2
* @ Param parity type int valid type values: N, E, O, and S
*/
Int set_Parity (int fd, int databits, int stopbits, int parity)
{
Struct termios options;
If (tcgetattr (fd, & options )! = 0 ){
Perror ("SetupSerial 1 ");
Return (FALSE );
}
Options. c_cflag & = ~ CSIZE;
Switch (databits)/* set the number of data digits */
{
Case 7:
Options. c_cflag | = CS7;
Break;
Case 8:
Options. c_cflag | = CS8;
Break;
Default:
Fprintf (stderr, "Unsupported data sizen"); return (FALSE );
}
Switch (parity)
{
Case 'N ':
Case 'N ':
Options. c_cflag & = ~ PARENB;/* Clear parity enable */
Options. c_iflag & = ~ INPCK;/* Enable parity checking */
Break;
Case 'O ':
Case 'O ':
Options. c_cflag | = (PARODD | PARENB);/* set it to an odd test */
Options. c_iflag | = INPCK;/* Disnable parity checking */
Break;
Case 'E ':
Case 'E ':
Options. c_cflag | = PARENB;/* Enable parity */
Options. c_cflag & = ~ PARODD;/* convert to an even test */
Options. c_iflag | = INPCK;/* Disnable parity checking */
Break;
Case's ':
Case's ':/* as no parity */
Options. c_cflag & = ~ PARENB;
Options. c_cflag & = ~ CSTOPB; break;
Default:
Fprintf (stderr, "Unsupported parityn ");
Return (FALSE );
}
/* Set the stop bit */
Switch (stopbits)
{
Case 1:
Options. c_cflag & = ~ CSTOPB;
Break;
Case 2:
Options. c_cflag | = CSTOPB;
Break;
Default:
Fprintf (stderr, "Unsupported stop bitsn ");
Return (FALSE );
}
/* Set input parity option */
If (parity! = 'N ')
Options. c_iflag | = INPCK;
Tcflush (fd, TCIFLUSH );
Options. c_cc [VTIME] = 150;/* set timeout of 15 seconds */
Options. c_cc [VMIN] = 0;/* Update the options and do it NOW */
If (tcsetattr (fd, TCSANOW, & options )! = 0)
{
Perror ("SetupSerial 3 ");
Return (FALSE );
}
Return (TRUE );
}



It should be noted that, if it is not a development terminal, it is just a serial port to transmit data, rather than a serial port for processing, the original Mode (Raw Mode) is used for communication. The setting method is as follows:

Options. c_lflag & = ~ (ICANON | ECHO | ECHOE | ISIG);/* Input */
Options. c_oflag & = ~ OPOST;/* Output */



Read/write serial port

After setting the serial port, it is easy to read and write the serial port.

· Send data

Char buffer [1024]; int Length; int nByte; nByte = write (fd, buffer, Length)



· Reading Serial Port Data

Use the file operation read function to read data. If the data is transmitted in Raw Mode, the number of characters returned by the read function is the number of characters actually received by the serial port. You can use functions of Operation files to Implement Asynchronous reading, such as fcntl or select operations.

Char buff [1024]; int Len; int readByte = read (fd, buff, Len );



Close serial port

Close the serial port is to close the file.

Close (fd );



Example

The following is a simple example of reading serial data. Some functions and header files defined above are used.

/*************************************** *******************************
Code Description: the serial port is used for testing. The sent data is a character,
However, the end symbol is not sent. Therefore, the end symbol is added after receiving the message.
I used a single-chip microcomputer to send data to the second serial port. The test passed.
**************************************** ******************************/
# Define FALSE-1
# Define TRUE 0
/*************************************** ******************************/
Int OpenDev (char * Dev)
{
Intfd = open (Dev, O_RDWR );
// | O_NOCTTY | O_NDELAY
If (-1 = fd)
{
Perror ("Can't Open Serial Port ");
Return-1;
}
Else
Return fd;
}
Int main (int argc, char ** argv ){
Int fd;
Int nread;
Char buff [512];
Char * dev = "/dev/ttyS1"; // Serial Port 2
Fd = OpenDev (dev );
Set_speed (fd, 19200 );
If (set_Parity (fd, 8, 1, 'n') = FALSE ){
Printf ("Set Parity Errorn ");
Exit (0 );
}
While (1) // read data cyclically
{
While (nread = read (fd, buff, 512)> 0)
{
Printf ("nLen % dn", nread );
Buff [nread + 1] = '';
Printf ("n % s", buff );
}
}
// Close (fd );
// Exit (0 );
}



References

Serial Programming Guide for POSIX Operating Systems

Download Code: Code
Related Article

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.